The Printf Function Is Used in Programming (Mainly in Lang
The Printf Function Is Used in Programming (Mainly in Lang
display output on the screen. It allows you to print text, numbers, or other values in a
formatted way.
Syntax: printf("format string", value1, value2, ...)
PRINT area, circumference // Output the calculated area and circumference END
Feat
For Loop While Loop Do-While Loop
ure
for
Synt (initialization; while
do { } while (condition);
ax condition; (condition)
increment)
Cond
ition Before the loop Before entering the After the loop executes
chec starts loop (guarantees at least 1 execution)
k
Whe When the number When you don't
When you need to execute the
n to of iterations is know the number
loop at least once
use known of iterations
Iterating over a Ensuring the loop executes at
Use Repeating while a
range or a fixed least once, even if the condition is
case condition is true
number of times false initially
Exa for (int i = 1;
while (i <= 5) do { } while (i <= 5)
mple i <= 5; i++)
Write a program in C to store elements in an array and print them.
Test Data :
Input 10 elements in the array :
element - 0 : 1
element - 1 : 1
element - 2 : 2
.......
Expected Output :
Elements in array are: 1 1 2 3 4 5 6 7 8 9
#include <stdio.h>
int main() {
int i;
scanf("%d", &arr[i]);
return 0;
//Initialize array
int temp = 0;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
printf("\n");
return 0;
Output:
52871
12578
#include <stdio.h>
int main()
scanf (" %d", &num); // take a positive number from the user
return 0;
Output:
An array is a data structure in programming that allows you to store multiple values of the same
type in a single variable. These values are stored in contiguous memory locations and are
accessed using an index or a key.
the creation of arrays involves declaring an array, defining its size, and assigning values to its
elements. Below, I'll explain how to create arrays in different programming languages,
particularly focusing on C as an example.
array initialization refers to assigning values to the elements of an array. It can be done at the
time of declaration or later in the code, and there are different ways to initialize arrays depending
on the requirements.
A one-dimensional array is a linear collection of elements, all of which are of the same type.
It's essentially a list of values, where each value can be accessed using an index. The index starts
from 0 and goes up to the size of the array minus one.
A multi-dimensional array is an array of arrays, meaning it has more than one dimension. The
most common types of multi-dimensional arrays are 2D arrays (two-dimensional arrays) and 3D
arrays (three-dimensional arrays), but arrays can have more dimensions.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // Declaring and initializing a 1D array with 5 elements
return 0;
}
The gets() function reads an entire line of text (a string) from the standard input (keyboard)
and stores it in a character array (string)
char str[100]; gets(str); // Input a string from the user printf("You entered: %s\n", str);
The puts() function writes a string to the standard output (screen), followed by a
newline character.
int getchar(void);
char ch; ch = getchar(); // Reads a single character from the user printf("You
entered: %c\n", ch);
The putchar() function writes a single character to the standard output (screen).
Definition of Recursion:
1. Base Case: A condition that stops the recursion from continuing indefinitely.
2. Recursive Case: The part of the function where it calls itself with modified
arguments, progressing towards the base case.
#include <stdio.h>
int main() {
int num;
return 0;
}
This type of function does not take any input and does not return any output. It is
defined with void as both the return type and the argument type.
This type of function accepts arguments (input) but does not return any value. It is
useful for performing operations like printing or modifying global variables based on the
input.
This type of function does not take any input but returns a value. It is useful for
computing a result without needing any parameters.
4. Function with Arguments and with Return Value
This type of function accepts input (arguments) and returns a value. It is used when you
need to pass data to the function and get a result based on those inputs.
1. Call by Value
Definition:
In Call by Value, the actual value of the argument is passed to the function. A copy of
the actual value is made and is used inside the function. Changes made to the
parameter inside the function do not affect the original variable outside the function.
#include <stdio.h>
int main() {
int num = 5;
addTen(num);
return 0;
2. Call by Reference
Definition:
In Call by Reference, instead of passing the value of the variable to the function, the
address (reference) of the variable is passed. This allows the function to modify the
actual variable. Changes made to the parameter inside the function directly affect the
original variable.
#include <stdio.h>
*num = *num + 10; // Modifying the value of num through its reference (pointer)
printf("Inside function, num after adding 10: %d\n", *num);
int main() {
data_type array_name[row_size][column_size];
In C, arrays are indexed starting from 0. So, for a 2D array of size m x n, valid indices
range from 0 to m-1 for rows and 0 to n-1 for columns.
A 2D array can be thought of as a matrix with rows and columns. The elements of a 2D
array are accessed using two indices — the row and the column.
Declaration of a 2D Array:
#include <stdio.h>
int main() {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
Preprocessor Directives in C
Preprocessor directives in C are special instructions that are processed before the
actual compilation of the program starts. These directives are preceded by a # symbol
and are used for various tasks, such as macro substitution, file inclusion, conditional
compilation, etc.
Definition:
Nested preprocessor directives refer to the use of one preprocessor directive inside
another preprocessor directive. These nested directives allow for more flexibility and
control in the pre-processing phase of the program.
For example, you might use a preprocessor directive inside an #if or #ifdef block or
within other directives to handle complex conditions or configurations. However, it's
important to note that preprocessor directives are processed before the actual program
is compiled, and they don’t have runtime behavior.
#include <stdio.h>
#endif
int main() {
#endif
return 0;
}
2. #define Directive
Definition:
Syntax:
1. Defining Constants:
2. Defining Macros:
Definition:
A void pointer is a special type of pointer that can point to any data type. It is a generic
pointer type, meaning it is not associated with any specific data type (like int*, char*,
etc.). It is often used for functions that can accept arguments of different data types or
when you want a pointer that can point to any data type without knowing the type in
advance.
Key Points:
A void* pointer cannot be dereferenced directly because the compiler does not
know the type of data it points to.
You must cast a void* pointer to another pointer type (such as int*, char*,
etc.) before dereferencing it.
It is useful in functions that need to accept different types of data, such as
malloc() in C, which returns a void* pointer.
Example:
#include <stdio.h>
void printValue(void *ptr, char type) { if (type == 'i') { printf("Integer value: %d\n", (int)ptr);
// Casting to int pointer } else if (type == 'f') { printf("Float value: %f\n", (float)ptr); //
Casting to float pointer } }
return 0;
Ii Const Pointer
Definition:
A const pointer is a pointer that points to a constant value, meaning the value it points
to cannot be changed through the pointer. The pointer itself can change to point to a
different address, but the value it points to remains constant.
1. Pointer to Constant Data: The pointer itself can be changed, but the value it
points to cannot be changed.
2. Constant Pointer: The value of the pointer cannot be changed after initialization,
but the data it points to can be modified.
Syntax:
Example:
#include <stdio.h>
int main() {
int x = 10, y = 20;
// Constant pointer
return 0;
}
Output: x: 15, y: 20
Null Pointer
Definition:
A null pointer is a pointer that does not point to any valid memory location. It is a
pointer with a value of NULL, which is a macro defined in <stddef.h> (or <stdio.h>),
and typically represents a pointer that is not initialized or is explicitly set to a non-
addressable value.
Example
#include <stdio.h>
int main() {
if (ptr == NULL) {
return 0;
In C, when we pass an array to a function, we are actually passing the address of the
first element of the array, not the entire array. This is because arrays in C are passed
as pointers to the first element, not as a whole structure. This means that functions can
access and modify the elements of the array directly.
There are two main ways to pass arrays to functions:
When passing an array to a function, only the pointer to the first element of the array
is passed, and the function can access all the elements of the array by using this
pointer.
#include <stdio.h>
int main() {
return 0;
You can also pass individual elements of the array (rather than the whole array) to a
function. This is done by passing the array element itself, which is a value (not a
pointer).
Example: Passing individual array elements to a function
#include <stdio.h>
int main() {
return 0;
}
Definition of Pointer:
A pointer is a variable that holds the memory address of another variable. The type of
pointer is defined by the type of data it points to. For example, a pointer to an integer is
of type int*, and a pointer to a character is of type char*.
The address-of operator (&) is used to get the memory address of a variable. It is
placed before the variable name and returns the memory address of the variable.
The dereferencing operator (*) is used to access the value at the memory address the
pointer is pointing to. It is placed before the pointer name and returns the value stored
at that memory location.
Diagram:
+-----------+ +-----------+
| Variable | | Pointer |
+-----------+ +-----------+
| a = 10 | | ptr = &a |
+-----------+ +-----------+
^^||
Address of `a`
Address of `ptr`
Program
#include <stdio.h>
int main() {
int a = 10; // Declare and initialize a variable
int *ptr; // Declare a pointer variable
return 0;
}
Function Pointers
A function pointer is a pointer that points to a function rather than a variable. This
allows you to dynamically select and call functions at runtime. Function pointers are
useful for callbacks, event handling, and when you need to pass functions as arguments
to other functions.
Definition:
A function pointer holds the memory address of a function and can be used to call that
function indirectly. It allows a program to call functions dynamically at runtime.
Definition of Structures in C
Syntax:
Structure Members
Structure members are the individual data elements inside a structure. Each member
can have a different data type. The members are accessed using the dot operator (.).
To access the members of a structure, we use the dot operator (.). You first specify
the structure variable (or instance) and then use the dot operator to access the
individual members.
Example Program:
#include <stdio.h>
#include <string.h> // For strcpy function
// Definition of structure
struct Student {
int roll_no;
char name[50];
float marks;
};
int main() {
// Creating and initializing a structure variable
struct Student student1;
return 0;
}
Definition of Unions in C
A union in C is a user-defined data type that allows storing different types of data in the
same memory location. Unlike structures, where each member gets its own memory, a
union allocates a shared memory space for all its members. This means that at any
given time, a union can hold only one value from its members, and the size of the union
is determined by the size of its largest member.
Syntax:
union union_name {
data_type member1;
data_type member2;
// other members
};
Union Members
A union can have multiple members of different types. However, all members share the
same memory space, which means modifying one member will affect the others, as
they all overlap in memory.
Just like in structures, union members are accessed using the dot operator (.). You
specify the union variable and then use the dot operator to access the individual
members
Example:
#include <stdio.h>
// Definition of union
union Data {
int i;
float f;
char c;
};
int main() {
// Declaring a union variable
union Data data;
return 0;
}
Explain in detail about how to read and write files in C?
Open and close the file
Read modes
getc( )
fscanf()
fread( )
Writing into the files
putc()
fprintf()
fwrite( )
Definition:
int main() {
int *ptr;
int n, i;
// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
return 0;
}
Definition:
calloc (contiguous allocation) is a function that allocates memory for an array of elements and
initializes the memory to zero. It is similar to malloc, but in addition to allocating memory, it
also sets all bytes to zero.
Syntax: void* calloc(size_t num_elements, size_t size_of_element);
Example:#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
return 0;
}
Output:
Enter number of elements: 5
The elements are initialized to 0:
0 0 0 0 0
(iii) realloc – Definition, Syntax, and Example
Definition:
realloc (reallocation) is a function used to resize a previously allocated memory block. It can
increase or decrease the size of a block of memory. If the new size is larger, the new memory
will be uninitialized (like in malloc). If the new size is smaller, the excess memory is
deallocated. If realloc fails to allocate the new size, it returns NULL, and the original memory
remains unchanged.
Syntax:void* realloc(void* ptr, size_t new_size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
return 0;
}
Programming Process
1. Analysis:
a. The problem is understood and analyzed.
b. Requirements and constraints are identified.
c. Inputs, outputs, and processes are clarified.
2. Design:
a. A plan is made for how to solve the problem.
b. Algorithms, data structures, and workflows are designed.
c. A clear structure (e.g., modular design) is planned for the program.
3. Coding:
a. The design is translated into code using a programming language.
b. The code is written, following the design specifications.
4. Testing:
a. The program is tested for correctness, performance, and reliability.
b. Test cases are created, and results are compared with expected
outcomes.
5. Maintenance:
a. After deployment, programs need updates, bug fixes, and performance
improvements.
b. Maintenance involves handling user feedback, fixing errors, and improving
functionality.
1. Problem Definition:
a. Understand the problem, including the requirements and the scope.
b. Identify the inputs, outputs, and the desired result.
2. Design:
a. Plan the approach, choose the best algorithm, and design data structures.
b. Use tools like pseudocode or flowcharts to sketch the solution.
3. Implementation:
a. Write the code in a programming language.
b. Follow the design to create the program.
4. Testing:
a. Check if the program works as expected by testing it with various inputs.
b. Ensure that the solution is correct and meets the problem’s requirements.
5. Debugging:
a. Find and fix errors or bugs in the code.
b. Use debugging tools to trace issues and correct them.
6. Optimization:
a. Make the program more efficient in terms of time and space.
b. Optimize the logic and reduce unnecessary operations.
7. Documentation:
a. Document the program to explain how it works, its inputs, outputs, and
logic.
b. This helps others (and your future self) understand the code.
Creative Thinking and Critical Thinking
Creative Thinking:
o Creative thinking involves thinking outside the box and coming up with
innovative solutions.
o In programming, this means finding new, unique approaches to solving
problems that others may not consider.
o For example, using an algorithm with better time complexity or coming up
with a clever data structure can be the result of creative thinking.
Critical Thinking:
o Critical thinking involves analyzing problems logically and evaluating
different solutions based on facts and data.
o It is essential for debugging and improving code, as it allows programmers
to evaluate the effectiveness of different algorithms or coding approaches
and make decisions about what will work best.
o Critical thinking helps in assessing trade-offs, such as between
performance and memory usage.
Both creative and critical thinking play a crucial role in programming. Creative thinking
helps generate solutions, while critical thinking helps refine those solutions and ensure
they are optimal.
Algorithm:
An algorithm is a step-by-step procedure or formula for solving a problem. It is a
blueprint for how the problem should be solved.
Example Algorithm to Add Two Numbers:
markdown
Copy code
1. Start
2. Read two numbers, A and B
3. Add A and B
4. Store the result in C
5. Print C
6. End
Pseudocode:
Pseudocode is a way to represent an algorithm using human-readable
statements that are not bound by the syntax of a specific programming language.
It is used to express the logic and steps of the solution in plain English.
Example Pseudocode for Adding Two Numbers:
mathematica
Copy code
Start
Read number1
Read number2
sum = number1 + number2
Print sum
End
Flowchart:
A flowchart is a diagrammatic representation of an algorithm. It uses shapes like
rectangles (for processes), diamonds (for decisions), and arrows (for flow
direction) to represent the steps and decision points in the process.
Example Flowchart for Adding Two Numbers:
sql
Copy code
+------------+
| Start |
+------------+
|
v
+------------+
| Read num1 |
+------------+
|
v
+------------+
| Read num2 |
+------------+
|
v
+------------+
| sum = num1 + num2 |
+------------+
|
v
+------------+
| Print sum |
+------------+
|
v
+------------+
| End |
+------------+
Definition of Operators:
Operators in C are used to perform various operations on variables and constants. They
are categorized into different types based on their functionality. These include
arithmetic, logical, relational, bitwise, assignment, and more.
Types of Operators in C
1. Arithmetic Operators
2. Logical Operators
3. Relational Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement Operators
7. Conditional (Ternary) Operator
8. Sizeof Operator
9. Pointer Operators
10. Comma Operator
1. Arithmetic Operators
Definition:
Arithmetic operators are used to perform basic arithmetic operations like addition,
subtraction, multiplication, division, and modulus.
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulus (remainder of division)
Example Program:
#include <stdio.h>
int main() {
int a = 10, b = 5;
sum = a + b; // Addition
diff = a - b; // Subtraction
prod = a * b; // Multiplication
quotient = a / b; // Division
remainder = a % b; // Modulus
return 0;
}
2. Logical Operators
Definition:
Logical operators are used to combine conditional expressions and return a true or false
value based on the evaluation.
Example Program:
#include <stdio.h>
int main() {
int x = 5, y = 10;
if (x < y || y < 0) {
}
return 0;
3. Relational Operators
Definition:
Relational operators are used to compare two values. They return true (1) if the
condition is true, and false (0) if the condition is false.
== : Equal to
!= : Not equal to
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
Example Program:
#include <stdio.h>
int main() {
4. Bitwise Operators
Definition:
Example Program:
#include <stdio.h>
int main() {
int a = 5, b = 9;
or = a | b; // Bitwise OR
return 0;
5. Assignment Operators
Definition:
= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
%= : Modulus and assign
Example Program:
#include <stdio.h>
return 0;
Definition:
The increment (++) and decrement (--) operators are used to increase or decrease the
value of a variable by 1.
++ : Increment operator
-- : Decrement operator
Example Program:
#include <stdio.h>
int main() {
int x = 10;
return 0;
}
Definition:
The ternary operator is a shorthand for the if-else statement. It evaluates a condition
and returns one of two values based on the result.
Example:
#include <stdio.h>
int main() {
int a = 5, b = 10;
return 0;
}
Write a program in C to find the sum of all elements of the array.
Test Data :
Input the number of elements to be stored in the array :3
C Program:
#include <stdio.h>
int main() {
int n, sum = 0;
scanf("%d", &arr[i]);
return 0;
}
Output:
1. For Loop
2. While Loop
3. Do-While Loop
Each loop serves a specific purpose and is used based on the requirements of the task.
1. For Loop
Definition:
The for loop is used when you know beforehand how many times the loop should run.
It has a specific number of iterations, and the condition is checked before every
iteration.
Syntax:
Example:
#include <stdio.h>
int main() {
printf("%d\n", i);
return 0;
}
2. While Loop
Definition:
The while loop is used when you don't know the number of iterations in advance but
need to repeat a block of code as long as a certain condition is true. The condition is
evaluated before each iteration.
Syntax:
while(condition) {
Example:
#include <stdio.h>
int main() {
int i = 1;
while(i <= 5) {
printf("%d\n", i);
return 0;
}
3. Do-While Loop
Definition:
The do-while loop is similar to the while loop, but the key difference is that the
condition is checked after the loop executes. This guarantees that the loop will always
execute at least once, regardless of whether the condition is true or false initially.
Syntax:
do {
} while(condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
return 0;
#include <stdio.h>
int main() {
int m, n, i, j;
return 0;
}
Output:
Definition:
The strlen() function is used to find the length of a string. It returns the number of
characters in a string excluding the null terminator ('\0').
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
return 0;
}
2. strcat() - Concatenate Strings
Definition:
The strcat() function is used to concatenate (combine) two strings. It appends the
source string to the end of the destination string.
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
return 0;
Definition:
The strstr() function searches for the first occurrence of a substring within a string. It
returns a pointer to the first occurrence of the substring, or NULL if the substring is not
found.
Syntax:
Example:
#include <stdio.h>
#include <string.h>
int main() {
if(result) {
} else {
return 0;
Definition:
The sprintf() function is used to format and store a string into a character array. It
works similarly to printf(), but instead of printing the output to the console, it stores it
in a string.
Syntax:
Example:
#include <stdio.h>
int main() {
char result[50];
return 0;
Definition:
The strcmp() function compares two strings lexicographically (based on ASCII values
of characters). It returns 0 if the strings are equal, a positive value if the first string is
lexicographically greater, or a negative value if the first string is lexicographically
smaller.
Syntax:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
if(result == 0) {
printf("Strings are equal.\n");
} else if(result < 0) {
printf("String 1 is less than String 2.\n");
} else {
printf("String 1 is greater than String 2.\n");
}
return 0;
}
Pointers in C:
A pointer is a variable that stores the memory address of another variable. In simpler
terms, a pointer "points" to a memory location where a value is stored. Pointers are
crucial in C because they provide direct access to memory, allowing us to work with
addresses, dynamic memory, and arrays more efficiently.
A pointer holds the memory address of a variable, rather than the variable's
value.
In C, we use the * (dereferencing) operator to access the value stored at the
address that the pointer is pointing to, and we use the & (address-of) operator to
get the address of a variable.
Pointer Syntax:
1. Declaration of Pointer:
a. To declare a pointer, you use the * symbol before the variable name,
indicating that it's a pointer.
int *ptr; // Pointer to an integer
2. Pointer Initialization:
a. A pointer must be initialized to point to a valid memory address. Typically,
this is done by using the address-of (&) operator on a variable.
int x = 10;
int *ptr = &x; // ptr now holds the address of x
3. Dereferencing a Pointer:
a. To access the value stored at the memory address that the pointer is
pointing to, we use the dereferencing operator (*).
int value = *ptr; // Dereferencing ptr gives us the value of x, which
is 10
Pointer Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr; // Declare a pointer to an integer
return 0;
}
Arrays in C are closely related to pointers. In fact, the name of an array is a constant
pointer to its first element. This means that you can use pointers to access array
elements.
How Arrays and Pointers are Related:
The name of an array (arr) refers to the address of the first element of the array.
Therefore, you can treat an array as a pointer to its first element, and you can
use pointer arithmetic to access array elements.
Array notation (arr[i]): This accesses the ith element of the array.
Pointer notation (*(arr + i)): This accesses the same ith element using a
pointer.
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // Array of 5 integers
int *ptr = arr; // Pointer points to the first element of arr
return 0;
}
Output:
sql
Copy code
First element: 1
Second element: 2
First element using pointer: 1
Second element using pointer: 2
Array elements using pointers:
1 2 3 4 5
The #include directive is used to include the contents of a specified file into the
program. It is commonly used to include standard libraries or user-defined header files.
Syntax:
Example:
The #define directive is used to define constants or macros. It defines a name and
associates it with a value or expression. When the compiler processes the code, it
replaces all occurrences of the name with the defined value or expression.
Syntax:
Example:
#define PI 3.14
Syntax:
#undef name
Example:
#define PI 3.14
#undef PI // Now PI is undefined
4. #ifdef - If Defined
The #ifdef directive is used to check whether a specific macro is defined. If the macro
is defined, the code between #ifdef and #endif is included in the compilation.
Otherwise, it is ignored.
Syntax:
#ifdef name
// Code to include if the macro is defined
#endif
Example:
c
Copy code
#define DEBUG
#ifdef DEBUG
printf("Debugging is enabled\n");
#endif
The #ifndef directive is used to check if a macro is not defined. If the macro is not
defined, the code between #ifndef and #endif is included in the compilation.
Syntax:
#ifndef name
// Code to include if the macro is not defined
#endif
Example:
#ifndef MAX_SIZE
#define MAX_SIZE 100
#endif
6. #if - If Condition
The #if directive is used to conditionally compile code based on a constant expression.
If the expression evaluates to a non-zero value, the code between #if and #endif is
included in the compilation.
Syntax:
#if expression
// Code to include if the expression is true
#endif
Example:
#define MAX_SIZE 50
#if MAX_SIZE > 40
printf("MAX_SIZE is greater than 40\n");
#endif
If the value of MAX_SIZE is greater than 40, the message will be printed.
The #else directive provides an alternative section of code to be included when the #if
or #ifdef condition fails (i.e., evaluates to false).
Syntax:
#if expression
// Code to include if the condition is true
#else
// Code to include if the condition is false
#endif
Example:
#define MAX_SIZE 30
#if MAX_SIZE > 40
printf("MAX_SIZE is greater than 40\n");
#else
printf("MAX_SIZE is less than or equal to 40\n");
#endif
The #elif directive is used to specify an additional condition to check if the previous
#if or #else condition fails. It is short for "else if".
Syntax:
#if expression1
// Code to include if expression1 is true
#elif expression2
// Code to include if expression1 is false and expression2 is true
#endif
Example:
#define MAX_SIZE 50
#if MAX_SIZE > 100
printf("MAX_SIZE is greater than 100\n");
#elif MAX_SIZE > 40
printf("MAX_SIZE is greater than 40 but less than or equal to
100\n");
#endif
The #endif directive marks the end of a block of conditional preprocessor directives
such as #if, #ifdef, or #ifndef.
Syntax:
#if condition
// Code to include if the condition is true
#endif
10. #error - Trigger Compilation Error
The #error directive is used to generate a compilation error with a custom error
message. This can be useful for debugging or handling configuration errors during the
preprocessing stage.
Syntax:
#error error_message
Example:
The #pragma directive is used to provide special instructions to the compiler. The
behavior of #pragma depends on the compiler being used, and different compilers may
support different pragmas. Some common uses of #pragma include disabling specific
warnings or optimizing code.
Syntax:
#pragma directive
Example:
2. File Pointers:
In C, file operations are carried out using file pointers. These are
variables that refer to files opened using the fopen() function. File
pointers store the address of the file and keep track of the current
position in the file for reading and writing.
c
Copy code
FILE *filePointer;
After opening a file with fopen(), the pointer will refer to the file,
and you can use it to perform file operations.
3. File Modes:
When opening a file, you must specify the file mode. The file mode
determines the operations that can be performed on the file. The
common modes are:
c
Copy code
FILE *fopen(const char *filename, const char *mode);
c
Copy code
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("File could not be opened\n");
}
Closing a File: Once file operations are done, you should close the
file using the fclose() function. It ensures that any buffered data is
written to the file and frees up resources associated with the file.
c
Copy code
int fclose(FILE *file);
You can read from a file using several functions, including fgetc(),
fgets(), and fread().
Example:
c
Copy code
char ch;
FILE *file = fopen("example.txt", "r");
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
Example:
c
Copy code
char str[100];
FILE *file = fopen("example.txt", "r");
while (fgets(str, sizeof(str), file)) {
printf("%s", str);
}
fclose(file);
Example:
char buffer[100];
FILE *file = fopen("example.txt", "rb");
fread(buffer, sizeof(char), 100, file);
fclose(file);
Writing to a File:
Example:
Example:
FILE *file = fopen("example.txt", "w");
fputs("Hello, World!", file);
fclose(file);
Example:
#include <stdio.h>
int main() {
// Declare variables to store information for two students
struct Student student1, student2;
printf("\nStudent 2 Information:\n");
printf("Name: %s\n", student2.name);
printf("Age: %d\n", student2.age);
printf("Total Marks: %.2f\n", student2.totalMarks);
return 0;
}
Output:
Input details for Student 1:
Name: Climacus
Age: 14
Total Marks: 189
Student 1 Information:
Name: Climacus
Age: 14
Total Marks: 189.00
Student 2 Information:
Name: Meredith
Age: 14
Total Marks: 192.00