0% found this document useful (0 votes)
25 views71 pages

The Printf Function Is Used in Programming (Mainly in Lang

Uploaded by

latheetha1mol
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)
25 views71 pages

The Printf Function Is Used in Programming (Mainly in Lang

Uploaded by

latheetha1mol
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
You are on page 1/ 71

The printf() function is used in programming (mainly in languages like C and C++) to

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, ...)

Example: printf("Hello, world!"); This will display: Hello, world!

The scanf() function is used in programming (mainly in languages like


C and C++) to get input from the user. It allows you to read data
(like numbers or text) entered by the user from the keyboard and store
it in variables.

 Syntax: scanf("format string", &variable1, &variable2, ...)


 Example: scanf("%d", &age); This will read an integer entered by
the user and store it in the age variable.

Storage class: In programming (especially in C and C++), storage


classes define the lifetime, scope, and visibility of variables or
functions. They specify how and where a variable or function is stored
in memory, and how long it exists during program execution.

Types of Storage Classes:

a. Auto (default):Local to the block or function where the


variable is declared.Exists only during the execution of the
block or function. Automatically allocated and deallocated
when entering and leaving the scope.
b. Register:Local to the block or function. Exists only during the execution
of the block or function. Stored in CPU registers (if available), rather than
RAM, for faster access. It’s a hint to the compiler, not a guarantee.
c. Static: Can be local or global. Exists for the entire duration of the
program, but the variable’s value is retained between function calls.The
variable is stored in a fixed location in memory, even if it’s declared inside
a function.
d. Extern: Global (visible across multiple files).Exists for the entire program’s
execution. Refers to a variable or function declared in another file. It
allows one file to access variables defined in another.

Write an algorithm to find the largest of three numbers.


Start
Read x, y, z
If x > y Then
If x > z Then
Print x
Else
Print z
Else
If y > z Then
Print y
Else
Print z
End

Write a pseudocode to calculate the area and circumference of a circle.

BEGIN READ r // Read the radius of the circle

INITIALISE pi = 3.14 // Set the value of pi

CALCULATE area = pi * r * r // Formula to calculate the area of the circle

CALCULATE circumference = 2 * pi * r // Formula to calculate the circumference of the circle

PRINT area, circumference // Output the calculated area and circumference END

Draw a flowchart to add two numbers and store it in another variable.


Comparison Table:

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 arr[10]; // Declare an array of size 10

int i;

// Read 10 elements into the array

printf("Input 10 elements in the array:\n");

for(i = 0; i < 10; i++) {

printf("element - %d : ", i);

scanf("%d", &arr[i]);

// Print the elements of the array

printf("Elements in array are: ");

for(i = 0; i < 10; i++) {

printf("%d ", arr[i]);

return 0;

Write a C program to get 5 elements and sort the array.


#include <stdio.h>
int main()

//Initialize array

int arr[] = {5, 2, 8, 7, 1};

int temp = 0;

//Calculate length of array arr

int length = sizeof(arr)/sizeof(arr[0]);

//Displaying elements of original array

printf("Elements of original array: \n");

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

printf("%d ", arr[i]);

//Sort the array in ascending order

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

for (int j = i+1; j < length; j++) {

if(arr[i] > arr[j]) {

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

printf("\n");

//Displaying elements of array after sorting

printf("Elements of array sorted in ascending order: \n");

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

printf("%d ", arr[i]);


}

return 0;

Output:

Elements of original array:

52871

Elements of array sorted in ascending order:

12578

Write a C program to print table for any number.

#include <stdio.h>

int main()

int num, i; // declare a variable

printf (" Enter a number to generate the table in C: ");

scanf (" %d", &num); // take a positive number from the user

printf ("\n Table of %d", num);

// use for loop to iterate the number from 1 to 10

for ( i = 1; i <= 10; i++)

printf ("\n %d * %d = %d", num, i, (num*i));

return 0;

Output:

Enter a number to generate the table in C: 7


Table of 7

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.

Program for One dimensional and multi-dimensional

#include <stdio.h>

int main() {

int arr[5] = {1, 2, 3, 4, 5}; // Declaring and initializing a 1D array with 5 elements

// Printing the elements of the 1D array

printf("One-dimensional array elements:\n");

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

printf("Element %d: %d\n", i, arr[i]);

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 *gets(char *str);

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.

Syntax: int puts(const char *str);

Ex: puts("Hello, World!"); // Prints: Hello, World!


The getchar() function reads a single character from the standard input (keyboard).

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).

int putchar(int ch);


putchar('A'); // Prints the character 'A'

Definition of Recursion:

Recursion is a programming technique where a function calls itself in order to solve a


problem. The problem is typically broken down into smaller, more manageable sub-
problems. A recursive function generally has two key components:

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>

// Function to calculate factorial using recursion


int factorial(int n) {
// Base case: if n is 0, return 1
if (n == 0) {
return 1;
} else {
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
}

int main() {
int num;

// Read input number


printf("Enter a number: ");
scanf("%d", &num);

// Calculate factorial using the recursive function


int result = factorial(num);

// Output the result


printf("Factorial of %d is: %d\n", num, result);

return 0;
}

1. Function with No Arguments and No Return Value

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.

2. Function with Arguments and No Return Value

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.

3. Function with No Arguments and with Return Value

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>

// Function using Call by Value

void addTen(int num) {

num = num + 10; // Modifying the value of num

printf("Inside function, num after adding 10: %d\n", num);

int main() {

int num = 5;

printf("Before function call, num: %d\n", num);

// Function call (Call by Value)

addTen(num);

// After function call


printf("After function call, num: %d\n", num); // The original num remains unchanged

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>

// Function using Call by Reference

void addTen(int *num) {

*num = *num + 10; // Modifying the value of num through its reference (pointer)
printf("Inside function, num after adding 10: %d\n", *num);

int main() {

int num = 5; printf("Before function call, num: %d\n", num);

// Function call (Call by Reference)


addTen(&num); // Passing the address of num

// After function call


printf("After function call, num: %d\n", num); // The original num is
modified
return 0;
}
Definition:

A multi-dimensional array in C is an array of arrays. It is a collection of data elements


arranged in a table-like structure with multiple rows and columns. Each element in a
multi-dimensional array is identified by two or more indices.

The most common types of multi-dimensional arrays are:

 2D Arrays (two-dimensional arrays)


 3D Arrays (three-dimensional arrays)
 And higher-dimensional arrays (e.g., 4D, 5D arrays, though rarely used in
practical applications).

Syntax for Declaring a Multi-Dimensional Array:

data_type array_name[row_size][column_size];

 data_type: Type of data (e.g., int, float).


 array_name: The name of the array.
 row_size: Number of rows in the array.
 column_size: Number of columns in the array.

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.

Example of a 2D Array (Matrix)

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:

int matrix[3][3]; // A 3x3 matrix (3 rows and 3 columns)


Program to Initialize and Print a 2D Array:

#include <stdio.h>

int main() {

// Declaration and initialization of a 2D array


int matrix[3][3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Printing the elements of the 2D array

printf("Elements of the 3x3 matrix are:\n");

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

for (int j = 0; j < 3; j++) {

printf("%d ", matrix[i][j]); // Accessing and printing each element

printf("\n"); // Move to the next line after each row

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.

Two important concepts related to preprocessor directives are:

1. Nested Preprocessor Directives


2. #define Directive
1. Nested Preprocessor Directives

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.

Example of Nested Preprocessor Directives:

#include <stdio.h>

#define DEBUG 1 // Define DEBUG as 1

#if DEBUG // Check if DEBUG is defined as 1

#define MESSAGE "Debugging is enabled." // Define a message if DEBUG is


enabled

#endif

int main() {

#if DEBUG // Nested preprocessor directive inside the main function

printf("%s\n", MESSAGE); // Print the message if DEBUG is enabled

#endif

return 0;

}
2. #define Directive

Definition:

The #define directive is used to define constants or macros in C. These constants or


macros are replaced by the preprocessor before compilation. It is one of the most
commonly used preprocessor directives. It can be used to define:

 Constants: Named values for constant expressions.


 Macros: Reusable code blocks or expressions that can take arguments.

Syntax:

1. Defining Constants:

#define CONSTANT_NAME value

2. Defining Macros:

#define MACRO_NAME(parameters) expression

(i) Void Pointer

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 } }

int main() { int num = 10; float fnum = 3.14;

printValue(&num, 'i'); // Passing an int


printValue(&fnum, 'f'); // Passing a float

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.

There are two types of const pointers:

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:

 Pointer to Constant Data:


const int *ptr;
 Constant Pointer:
int *const ptr;

 Constant Pointer to Constant Data:


const int *const ptr;

Example:

#include <stdio.h>

int main() {
int x = 10, y = 20;

// Pointer to constant data

const int *ptr1 = &x;

ptr1 = &y; // Allowed, but *ptr1 cannot be modified

// Constant pointer

int *const ptr2 = &x;

*ptr2 = 15; // Allowed, but ptr2 cannot point to another address

// Pointer to constant data and constant pointer

const int *const ptr3 = &x;

// ptr3 = &y; // Error: Cannot change the address of ptr3

// *ptr3 = 20; // Error: Cannot modify the value pointed by ptr3

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

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() {

int *ptr = NULL; // Initialize pointer as NULL

if (ptr == NULL) {

printf("The pointer is NULL, no memory allocated.\n");

// Uncommenting the following line would cause a runtime error

// printf("Dereferencing null pointer: %d\n", *ptr); // Undefined behavior

return 0;

Passing Array Elements to a Function in C

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:

1. Passing the entire array to the function


2. Passing individual elements of the array to the function

1. Passing the Entire Array to a Function

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.

Example: Passing the entire array to a function

#include <stdio.h>

void printArray(int arr[], int size) {

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

printf("Element at index %d: %d\n", i, arr[i]);

int main() {

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

int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

printArray(arr, size); // Pass the entire array to the function

return 0;

2. Passing Individual Array Elements to a Function

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>

void printElement(int element) {

printf("Element: %d\n", element);

int main() {

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

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

printElement(arr[i]); // Passing each element of the array to the function

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*.

Syntax: data_type *pointer_name;

1. Address-of Operator (&)

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

ptr = &a; // Store the address of a in ptr

printf("Value of a: %d\n", a); // Print value of a


printf("Address of a: %p\n", &a); // Print address of a
printf("Value of ptr (address of a): %p\n", ptr); // Print the address stored in ptr
printf("Value at ptr (value of a): %d\n", *ptr); // Dereference ptr to get the value of a

// Modify the value of 'a' using the pointer


*ptr = 20; // Set value at the memory address pointed by ptr to 20
printf("New value of a after modification: %d\n", a); // Print new value of a

return 0;
}

Pointers to Array Elements

In C, pointers can also be used to access array elements. An array is essentially a


pointer to the first element in memory, so pointers and arrays are closely related. This
allows for efficient and direct access to elements of an array using pointers.
Definition:

A pointer to an array element is a pointer that holds the memory address of an


individual element in an array, allowing direct access to and manipulation of the array
elements.

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

A structure in C is a user-defined data type that allows grouping of variables of different


types under a single name. It is used to represent a record, where each member of the
structure can hold different types of data. Structures help in organizing complex data in
a more manageable way.

Syntax:

struct structure_name { data_type member1; data_type member2; // other members };

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 (.).

Accessing the Members (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;

// Assigning values to structure members


student1.roll_no = 101;
strcpy(student1.name, "John Doe");
student1.marks = 85.5;
// Accessing and printing the values of structure members
printf("Roll Number: %d\n", student1.roll_no);
printf("Name: %s\n", student1.name);
printf("Marks: %.2f\n", student1.marks);

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.

Accessing the Members (Using the Dot Operator)

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;

// Assigning values to the union members


data.i = 10; // Assigning value to 'i'
printf("Value of i: %d\n", data.i);

data.f = 3.14; // Assigning value to 'f' (this overwrites 'i')


printf("Value of f: %.2f\n", data.f);

data.c = 'A'; // Assigning value to 'c' (this overwrites 'f')


printf("Value of c: %c\n", data.c);
// Note: After assigning a new value to a union member, the previous value is
overwritten
printf("Value of i after assigning 'c': %d\n", data.i); // The value of i is now undefined
printf("Value of f after assigning 'c': %.2f\n", data.f); // The value of f is now undefined

return 0;
}
Explain in detail about how to read and write files in C?
Open and close the file

Read modes

Reading the files

 getc( )
 fscanf()
 fread( )
Writing into the files

 putc()
 fprintf()
 fwrite( )

(i) malloc – Definition, Syntax, and Example

Definition:

malloc (memory allocation) is a standard library function in C used to dynamically allocate a


block of memory at runtime. The memory is uninitialized, meaning it can contain garbage values
until explicitly initialized. The allocated memory can be used to store variables whose sizes are
not known at compile time.
Syntax:void* malloc(size_t size);
Example:#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
int n, i;

// Ask user for number of elements


printf("Enter number of elements: ");
scanf("%d", &n);

// Dynamically allocate memory for 'n' integers


ptr = (int*) malloc(n * sizeof(int));

// Check if memory allocation was successful


if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program if allocation fails
}

// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}

// Print the elements


printf("Entered elements are:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(ptr);

return 0;
}

Output:Enter number of elements: 5


Enter 5 integers:
1 2 3 4 5
Entered elements are:
1 2 3 4 5
(ii) calloc – Definition, Syntax, and Example

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;

// Ask user for number of elements


printf("Enter number of elements: ");
scanf("%d", &n);

// Dynamically allocate memory using calloc


ptr = (int*) calloc(n, sizeof(int));

// Check if memory allocation was successful


if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program if allocation fails
}

// Print the elements (should be initialized to 0)


printf("The elements are initialized to 0:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(ptr);

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;

// Ask user for number of elements


printf("Enter number of elements: ");
scanf("%d", &n);

// Dynamically allocate memory using malloc


ptr = (int*) malloc(n * sizeof(int));

// Check if memory allocation was successful


if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program if allocation fails
}

// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}

// Ask user for new size to resize the array


printf("Enter new number of elements: ");
scanf("%d", &n);

// Reallocate memory using realloc


ptr = (int*) realloc(ptr, n * sizeof(int));

// Check if memory reallocation was successful


if (ptr == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
// Input new elements
printf("Enter the new %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}

// Print the elements


printf("All elements are:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(ptr);

return 0;
}

Output:Enter number of elements: 3


Enter 3 integers:
1 2 3
Enter new number of elements: 5
Enter the new 5 integers:
4 5 6 7 8
All elements are:
1 2 3 4 5

Problem Solving through Programming

Problem-solving through programming refers to the process of using programming skills


to understand, break down, and solve problems. It involves thinking logically and
systematically, applying the correct algorithms, and writing code to implement those
solutions. Programming allows us to automate repetitive tasks, solve complex problems,
and improve processes.
Steps in Problem Solving through Programming:

1. Understand the Problem: The first step in problem-solving is to clearly


understand the problem statement. This involves identifying the inputs, outputs,
and requirements of the problem.
2. Plan the Solution: After understanding the problem, the next step is to create a
structured plan. This can be done using different techniques such as algorithms,
pseudocode, or flowcharts.
3. Write the Code: Once the solution is planned, the next step is to implement it
using a programming language. The code should be clean, well-documented,
and modular.
4. Test the Solution: After writing the code, it's essential to test it with different
inputs to ensure it solves the problem correctly and efficiently.
5. Debug the Code: If the code doesn't work as expected, debugging helps find
and fix errors. This can be done using various tools and techniques like print
statements, IDE debuggers, and logic tracing.
6. Optimize the Solution: Once the code works correctly, optimization involves
improving the efficiency, readability, and performance of the code.
7. Document the Solution: Proper documentation of the solution helps future
developers (or even your future self) understand the logic, the approach, and the
functionality of the code.

Programming Process

The programming process is a series of steps taken by a programmer to turn an idea


into an executable program. This includes analysis, design, coding, testing, and
maintenance.

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.

Phases of Programming Task

The phases of programming can be described as follows:

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.

List of Arithmetic Operators:

 + : Addition
 - : Subtraction
 * : Multiplication
 / : Division
 % : Modulus (remainder of division)

Example Program:

#include <stdio.h>

int main() {

int a = 10, b = 5;

int sum, diff, prod, quotient, remainder;

sum = a + b; // Addition

diff = a - b; // Subtraction

prod = a * b; // Multiplication

quotient = a / b; // Division

remainder = a % b; // Modulus

printf("Sum: %d\n", sum);

printf("Difference: %d\n", diff);

printf("Product: %d\n", prod);

printf("Quotient: %d\n", quotient);

printf("Remainder: %d\n", remainder);

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.

List of Logical Operators:

 && : Logical AND


 || : Logical OR
 ! : Logical NOT

Example Program:

#include <stdio.h>

int main() {

int x = 5, y = 10;

if (x < y && y > 0) {

printf("Logical AND: Condition is TRUE\n");

if (x < y || y < 0) {

printf("Logical OR: Condition is TRUE\n");

if (!(x > y)) {

printf("Logical NOT: Condition is TRUE\n");

}
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.

List of Relational Operators:

 == : 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() {

int a = 10, b = 20;

printf("a == b: %d\n", a == b); // Equal to

printf("a != b: %d\n", a != b); // Not equal to

printf("a > b: %d\n", a > b); // Greater than

printf("a < b: %d\n", a < b); // Less than

printf("a >= b: %d\n", a >= b); // Greater than or equal to

printf("a <= b: %d\n", a <= b); // Less than or equal to


return 0;

4. Bitwise Operators

Definition:

Bitwise operators are used to perform operations on individual bits of data.

List of Bitwise Operators:

 & : Bitwise AND


 | : Bitwise OR
 ^ : Bitwise XOR
 ~ : Bitwise NOT
 << : Left shift
 >> : Right shift

Example Program:

#include <stdio.h>

int main() {

int a = 5, b = 9;

int and, or, xor, leftShift, rightShift;

and = a & b; // Bitwise AND

or = a | b; // Bitwise OR

xor = a ^ b; // Bitwise XOR

leftShift = a << 1; // Left shift (multiply by 2)

rightShift = a >> 1; // Right shift (divide by 2)

printf("a & b: %d\n", and);


printf("a | b: %d\n", or);

printf("a ^ b: %d\n", xor);

printf("a << 1: %d\n", leftShift);

printf("a >> 1: %d\n", rightShift);

return 0;

5. Assignment Operators

Definition:

Assignment operators are used to assign values to variables.

List of Assignment Operators:

 = : Simple assignment
 += : Add and assign
 -= : Subtract and assign
 *= : Multiply and assign
 /= : Divide and assign
 %= : Modulus and assign

Example Program:

#include <stdio.h>

int main() { int a = 10;

a += 5; // Add and assign (a = a + 5)


printf("a += 5: %d\n", a);

a -= 3; // Subtract and assign (a = a - 3)


printf("a -= 3: %d\n", a);

a *= 2; // Multiply and assign (a = a * 2)


printf("a *= 2: %d\n", a);
a /= 4; // Divide and assign (a = a / 4)
printf("a /= 4: %d\n", a);

return 0;

6. Increment and Decrement Operators

Definition:

The increment (++) and decrement (--) operators are used to increase or decrease the
value of a variable by 1.

List of Increment and Decrement Operators:

 ++ : Increment operator
 -- : Decrement operator

Example Program:

#include <stdio.h>

int main() {
int x = 10;

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

printf("After x++: %d\n", x);

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

printf("After --x: %d\n", x);

return 0;
}

7. Conditional (Ternary) Operator

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;

int result = (a > b) ? a : b; // If a > b, result = a; otherwise, result = b

printf("The greater value is: %d\n", result);

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;

// Input number of elements in the array

printf("Input the number of elements to be stored in the array: ");


scanf("%d", &n);

int arr[n]; // Declare the array of size 'n'

// Input elements into the array

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

printf("element - %d : ", i);

scanf("%d", &arr[i]);

// Calculate the sum of all elements in the array

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

sum += arr[i]; // Add each element to sum

// Output the result

printf("Sum of all elements stored in the array is : %d\n", sum);

return 0;

}
Output:

Sum of all elements stored in the array is : 15

Looping in C refers to the repeated execution of a block of code until a specified


condition is met. It is an essential concept used to perform repetitive tasks efficiently
without having to write the same code multiple times.

There are three main types of loops in C:

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:

for(initialization; condition; increment/decrement) {

// Code block to be executed

Example:

#include <stdio.h>

int main() {

// Print numbers from 1 to 5

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

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) {

// Code block to be executed

Example:

#include <stdio.h>

int main() {

int i = 1;

// Print numbers from 1 to 5

while(i <= 5) {

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

i++; // Increment the value of 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 {

// Code block to be executed

} while(condition);

Example:

#include <stdio.h>

int main() {

int i = 1;

// Print numbers from 1 to 5

do {

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

i++; // Increment the value of i

} while(i <= 5);

return 0;

C Program to Perform Matrix Addition:

#include <stdio.h>

int main() {
int m, n, i, j;

// Input number of rows and columns for matrices


printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);

// Declare two matrices and the result matrix


int matrix1[m][n], matrix2[m][n], result[m][n];

// Input elements for matrix1


printf("Enter elements of matrix 1:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("Enter element [%d][%d]: ", i+1, j+1);
scanf("%d", &matrix1[i][j]);
}
}

// Input elements for matrix2


printf("Enter elements of matrix 2:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("Enter element [%d][%d]: ", i+1, j+1);
scanf("%d", &matrix2[i][j]);
}
}

// Perform matrix addition


for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result matrix


printf("\nSum of Matrix 1 and Matrix 2 is:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

Output:

Sum of Matrix 1 and Matrix 2 is:


8 10 12
14 16 18

1. strlen() - String Length

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:

size_t strlen(const char *str);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello, World!";

int length = strlen(str);

printf("Length of the string is: %d\n", length);

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:

char *strcat(char *dest, const char *src);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str1[50] = "Hello";

char str2[] = " World!";

strcat(str1, str2); // Concatenate str2 to str1

printf("After concatenation: %s\n", str1);

return 0;

3. strstr() - Find Substring

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:

char *strstr(const char *haystack, const char *needle);

Example:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Programming in C is fun!";

char sub[] = "in";

char *result = strstr(str, sub); // Search for substring "in"

if(result) {

printf("Substring found at position: %ld\n", result - str);

} else {

printf("Substring not found\n");

return 0;

4. sprintf() - Formatted String Output

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:

int sprintf(char *str, const char *format, ...);

Example:

#include <stdio.h>

int main() {

int age = 25;

char name[] = "John";

char result[50];

sprintf(result, "Name: %s, Age: %d", name, age);

printf("Formatted string: %s\n", result);

return 0;

5. strcmp() - Compare Two Strings

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.

int strcmp(const char *str1, const char *str2);

Syntax:

int strcmp(const char *str1, const char *str2);


Example:

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

int main() {
char str1[] = "apple";
char str2[] = "banana";

int result = strcmp(str1, str2);

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.

How Pointers Work:

 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

ptr = &x; // Store the address of x in ptr

// Output the address of x and its value through the pointer


printf("Address of x: %p\n", ptr); // Prints the address of x
printf("Value of x: %d\n", *ptr); // Dereferencing ptr gives the
value of x

return 0;
}

Accessing Arrays Using Pointers:

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 and Pointer Relationship:

 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.

Both of these expressions are equivalent.

Example: Accessing Array Elements Using Pointers:

#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

// Access elements using array notation


printf("First element: %d\n", arr[0]);
printf("Second element: %d\n", arr[1]);

// Access elements using pointer arithmetic


printf("First element using pointer: %d\n", *ptr); // Equivalent
to arr[0]
printf("Second element using pointer: %d\n", *(ptr + 1)); //
Equivalent to arr[1]

// Loop through the array using pointers


printf("Array elements using pointers:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Equivalent to arr[i]
}

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

Advantages of Using Pointers with Arrays:

1. Efficiency: Accessing elements via pointers can be more efficient, especially in


the case of large arrays, because pointers avoid copying the values.
2. Dynamic Memory Allocation: Pointers allow dynamic allocation and
deallocation of memory, making it more flexible when working with arrays.
3. Pointer Arithmetic: You can perform pointer arithmetic to navigate through an
array, offering more control over how elements are accessed and manipulated.

1. #include - Include a Header File

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:

#include <file_name> // For system header files

#include "file_name" // For user-defined header files

Example:

#include <stdio.h> // Standard library to include input/output


functions
#include "my_header.h" // User-defined header
2. #define - Define a Macro

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:

#define name value

 Example:

#define PI 3.14

3. #undef - Undefine a Macro

The #undef directive is used to undefine a macro, removing its


definition. After using #undef, the macro is no longer recognized by
the compiler.

 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

5. #ifndef - If Not Defined

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.

7. #else - Else Clause

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

 Since MAX_SIZE is 30, the second message will be printed.


8. #elif - Else If

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

 Since MAX_SIZE is 50, the second message will be printed.

9. #endif - End of Conditional Preprocessing

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:

#if MAX_SIZE > 100


#error "MAX_SIZE should not exceed 100!"
#endif

11. #pragma - Special Compiler Instructions

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:

#pragma warning(disable : 4996) // Disable specific compiler warning


File Handling in C

File handling in C allows programs to interact with files on the disk,


enabling them to read from and write to files. Files are typically
used to store data that needs to be preserved across program
executions, and file handling allows us to manage data in files in a
controlled manner.
1. Definition:

In C, file handling is done through a set of standard library


functions. A file can be opened, read, written, or closed. Files can
be either text files or binary files, and C provides specific
functions to manage them. Files are represented by file pointers,
which refer to the file in memory while the program interacts with it.

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.

A file pointer is declared as:

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:

 "r" – Open for reading. The file must exist.


 "w" – Open for writing. If the file exists, it is truncated. If
it does not exist, a new empty file is created.
 "a" – Open for appending. Writes are done at the end of the file.
If the file does not exist, a new file is created.
 "rb" – Open for reading in binary mode. The file must exist.
 "wb" – Open for writing in binary mode. If the file exists, it is
truncated; if it does not exist, a new empty file is created.
 "ab" – Open for appending in binary mode.
 "r+" – Open for reading and writing. The file must exist.
 "w+" – Open for reading and writing. If the file exists, it is
truncated. If it does not exist, a new empty file is created.
 "a+" – Open for reading and appending. If the file does not
exist, a new file is created.
 "rb+" – Open for reading and writing in binary mode.
 "wb+" – Open for reading and writing in binary mode, truncating
the file if it exists.

4. Opening and Closing a File:

Opening a File: To open a file in C, you use the fopen() function. It


returns a file pointer that is used in subsequent operations. If the
file cannot be opened, fopen() returns NULL.

c
Copy code
FILE *fopen(const char *filename, const char *mode);

Example of opening a file for reading:

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);

Example of closing a file:


c
Copy code
fclose(file);

5. Reading and Writing a File:

Reading from a File:

You can read from a file using several functions, including fgetc(),
fgets(), and fread().

 fgetc() – Reads one character from the file.


c
Copy code
int fgetc(FILE *file);

Example:

c
Copy code
char ch;
FILE *file = fopen("example.txt", "r");
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);

 fgets() – Reads a string from the file (up to a specified limit


or until a newline is encountered).
c
Copy code
char *fgets(char *str, int n, FILE *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);

 fread() – Reads binary data from a file into a buffer.


c
Copy code
size_t fread(void *ptr, size_t size, size_t count, FILE *file);

Example:

char buffer[100];
FILE *file = fopen("example.txt", "rb");
fread(buffer, sizeof(char), 100, file);
fclose(file);

Writing to a File:

To write to a file, you can use fputc(), fputs(), and fwrite().

 fputc() – Writes a single character to the file.


int fputc(int char, FILE *file);

Example:

FILE *file = fopen("example.txt", "w");


fputc('A', file);
fclose(file);

 fputs() – Writes a string to the file.


int fputs(const char *str, FILE *file);

Example:
FILE *file = fopen("example.txt", "w");
fputs("Hello, World!", file);
fclose(file);

 fwrite() – Writes binary data from a buffer to the file.


size_t fwrite(const void *ptr, size_t size, size_t count, FILE *file);

Example:

FILE *file = fopen("example.txt", "wb");


int arr[] = {1, 2, 3, 4};
fwrite(arr, sizeof(int), 4, file);
fclose(file);
2. Create a structure called "Student" with members name, age, and total marks.
Write a C program to input data for two students, display their information,
and find the average of total marks.

#include <stdio.h>

// Define the structure "Student"


struct Student {
char name[50];
int age;
float totalMarks;
};

int main() {
// Declare variables to store information for two students
struct Student student1, student2;

// Input data for the first student


printf("Input details for Student 1:\n");
printf("Name: ");
scanf("%s", student1.name); // Assuming names do not contain spaces
printf("Age: ");
scanf("%d", &student1.age);
printf("Total Marks: ");
scanf("%f", &student1.totalMarks);

// Input data for the second student


printf("\nInput details for Student 2:\n");
printf("Name: ");
scanf("%s", student2.name); // Assuming names do not contain spaces
printf("Age: ");
scanf("%d", &student2.age);
printf("Total Marks: ");
scanf("%f", &student2.totalMarks);

// Display information for both students


printf("\nStudent 1 Information:\n");
printf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("Total Marks: %.2f\n", student1.totalMarks);

printf("\nStudent 2 Information:\n");
printf("Name: %s\n", student2.name);
printf("Age: %d\n", student2.age);
printf("Total Marks: %.2f\n", student2.totalMarks);

// Calculate and display the average total marks


float averageMarks = (student1.totalMarks + student2.totalMarks) / 2;
printf("\nAverage Total Marks: %.2f\n", averageMarks);

return 0;
}

Output:
Input details for Student 1:
Name: Climacus
Age: 14
Total Marks: 189

Input details for Student 2:


Name: Meredith
Age: 14
Total Marks: 192

Student 1 Information:
Name: Climacus
Age: 14
Total Marks: 189.00

Student 2 Information:
Name: Meredith
Age: 14
Total Marks: 192.00

Average Total Marks: 190.50

You might also like