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

Problem Solving Through Programming in C

The document provides an overview of pointers in C programming, explaining their definition, benefits, and usage in accessing and manipulating memory. It covers key concepts such as pointer arithmetic, pass by reference, and examples of pointer applications including array manipulation and file handling. Additionally, it discusses sequential and random access methods for file operations, highlighting their advantages and disadvantages.

Uploaded by

kafkaesqx
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)
4 views31 pages

Problem Solving Through Programming in C

The document provides an overview of pointers in C programming, explaining their definition, benefits, and usage in accessing and manipulating memory. It covers key concepts such as pointer arithmetic, pass by reference, and examples of pointer applications including array manipulation and file handling. Additionally, it discusses sequential and random access methods for file operations, highlighting their advantages and disadvantages.

Uploaded by

kafkaesqx
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

Tab 2

Problem Solving Through


Programming in C

Module-V

Group Members:
Adnan H
Ahammed Naseef
Harinand B S
Fatima Mohamed Subair
Dinu Yasin S
Jihan Janees
Muhammed Noufal
POINTER
A pointer is a derived data type in C.
●​ It is built from one of the fundamental data types available in C.
●​ Pointers contain memory addresses as their values.
●​ Since these memory addresses are the locations in the computer memory where
program instructions and data are stored, pointers can be used to access and
manipulate data stored in the memory.
●​ It has added power and flexibility to the language.
●​ Although they appear little confusing and difficult to understand for a beginner, they
are a
●​ powerful tool and handy to use once they are mastered.

Pointers are used frequently in C, as they offer a number of benefits to the programmers.
They include:
1. Pointers can be used to return multiple values from a function via function
arguments.
2. Pointers permit references to functions and thereby facilitating passing of functions
as arguments to other functions.
3. The use of pointer arrays to character strings results in saving of data storage space in
memory.
4. Pointers allow C to support dynamic memory management.
5. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.

The computer's memory is a sequential collection of storage cells.

●​ Whenever we declare a variable, the system allocates, somewhere in the memory,


an appropriate location to hold the value of the variable.
●​ Since, every byte has a unique address number, this location will have its own
address number.

●​ This statement instructs the system to find a location for the integer variable quantity
and puts the value 179 in that location.
●​ Let us assume that the system has chosen the address location 5000 for quantity.
●​ During execution of the program, the system always associates the name quantity
with the address 5000.

●​ We may have access to the value 179 by using either the name quantity or the
address 5000.
●​ Since memory addresses are simply numbers, they can be assigned to some
variables, that can be stored in memory, like any other variable.
●​ Such variables that hold memory addresses are called pointer variables .
●​ A pointer variable is, therefore, nothing but a variable that contains an address, which
is a location of another variable in memory.

●​ Remember, since a pointer is a variable, its value is also stored in the memory in
another
●​ location.
●​ Suppose, we assign the address of quantity to a variable p .
●​ The link between the variables p and quantity can be visualized as shown in above
figure
●​ The address of p is 5048.
●​ Since the value of the variable p is the address of the variable quantity, we may
access the value of quantity by using the value of p and therefore, we say that the
variable p 'points' to the variable quantity .
●​ Thus, p gets the name 'pointer'.

Underlying Concepts of Pointers


Pointers are built on the three underlying concepts as illustrated below:
●​ Memory addresses within a computer are referred to as pointer constants.
●​ We cannot change them; we can only use them to store data values.
●​ They are like house numbers.
●​ We cannot save the value of a memory address directly.
●​ We can only obtain the value through the variable stored there using the address
operator (&).
●​ The value thus obtained is known as pointer value.
●​ The pointer value (i.e. the address of a variable) may change from one run of the
program to another.
●​ Once we have a pointer value, it can be stored into another variable.
●​ The variable that contains a pointer value is called a pointer variable.

Accessing the Address of a Variable

●​ The actual location of a variable in the memory is system dependent and therefore,
the address of a variable is not known to us immediately.
●​ How can we then determine the address of a variable? This can be done with the
help of the operator & available in C.
●​ We have already seen the use of this address operator in the scanf function.
●​ The operator & immediately preceding a variable returns the address of the variable
associated with it.

For example, the statement p= &quantity; would assign the address 5000 (the location of
quantity) to the variable p.

The & operator can be remembered as 'address of'.

The & operator can be used only with a simple variable or an array element.

The following are illegal use of address operator:

1. &125 (pointing at constants).

2. int x[10];

&x (pointing at array names).


3. &(x+y) (pointing at expressions).

If x is an array, then expressions such as

&x|0] and &x|i+3] are valid and represent the addresses of 0th and (i+3)th elements of x.

Array Access Using Pointers


Arrays and pointers are closely related. The name of an array itself acts as a pointer
to its first element.

Key Concept:

If arr is an array, then:

●​ arr = &arr[0]
●​ arr[i] = *(arr + i)

Example:

#include <stdio.h>

int main() {

int arr[5] = {10, 20, 30, 40, 50};

int *p;

p = arr;

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

printf("Element %d = %d\n", i, *(p + i));

return 0;

Explanation:

●​ Pointer p stores base address of array


●​ (p + i) moves to next memory location
●​ *(p + i) gives value at that position

Important Points:

●​ Pointer arithmetic depends on data type size


●​ p + 1 moves by sizeof(int) bytes
●​ Faster than index-based access in some cases

Pointer Arithmetic
Pointer arithmetic allows moving through memory locations.

Operations:

●​ Increment: p++
●​ Decrement: p--
●​ Addition: p + n
●​ Subtraction: p - n

Example:

#include <stdio.h>

int main() {

int arr[3] = {5, 10, 15};

int *p = arr;

printf("%d\n", *p); // 5

p++;

printf("%d\n", *p); // 10

p++;

printf("%d\n", *p); // 15

return 0;

}
Pass by Reference (Using Pointers)
In this method, the address of the variable is passed.​
So, changes inside the function affect the original variable.

Example:

#include <stdio.h>
void modify(int *x) {
*x = *x + 10;
}

int main() {
int a = 5;
modify(&a);

printf("Value of a = %d", a); // Output: 15

return 0;
}

Effect of Pass by Reference


Advantages:

●​ Original data can be modified


●​ No extra memory used (efficient)
●​ Multiple values can be returned
●​ Useful for large data structures

Example: Swapping Two Numbers

#include <stdio.h>

void swap(int *a, int *b) {


int temp;
temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 3, y = 7;

swap(&x, &y);

printf("After swap: x = %d, y = %d", x, y);

return 0;
}
Simple Programs Using Pointers

(1) Sum of Elements in Array

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int sum = 0;

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


sum += *(p + i);
}

printf("Sum = %d", sum);

return 0;
}

(2) Find Maximum Element

#include <stdio.h>

int main() {
int arr[5] = {12, 45, 7, 89, 23};
int *p = arr;
int max = *p;

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


if(*(p + i) > max) {
max = *(p + i);
}
}
printf("Maximum = %d", max);

return 0;
}

(3)Reverse an array

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *start = arr;
int *end = arr + 4;
int temp;

while(start < end) {


temp = *start;
*start = *end;
*end = temp;

start++;
end--;
}

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


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

return 0;
}
File Handling in C
File handling allows data to be stored permanently on disk. C provides functions in
<stdio.h> to perform operations on files using file pointers (FILE *fp).

Operation Function Purpose

Open fopen() Opens a file for reading/writing/appending

Close fclose() Closes an opened file

Read fscanf(), fgets(), Reads data from a file


fread()

Write fprintf(), fputs(), Writes data to a file


fwrite()

Append fopen() with "a" mode Adds data at the end of a file

[Link] a file

fopen() establishes a connection between the program and the file.

SYNTAX:
FILE *fp;
fp = fopen("[Link]", "mode");

COMMON MODES

Mode Meaning File must


exist?

"r" Read Yes

"w" Write (creates new file or overwrites existing) No

"a" Append No

"r+" Read and write Yes

"w+" Read and write (overwrites) No

"a+" Read and append No


EXAMPLE:
FILE *fp;
fp = fopen("[Link]", "w");
if(fp == NULL) {
printf("File not found!");
}

[Link] a File

fclose() terminates the connection between the file and the program, ensuring data is
saved properly.

SYNTAX:
fclose(fp);

EXAMPLE:
FILE *fp = fopen("[Link]", "w");
fprintf(fp, "Hello World!");
fclose(fp);

4. Reading from a file

Methods

1.​ Character by character — fgetc()


2.​ String by string — fgets()
3.​ Formatted data — fscanf()
4.​ Binary data — fread()

EXAMPLES:

// Using fgetc()

char ch;

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

while((ch = fgetc(fp)) != EOF)

putchar(ch);

fclose(fp);
// Using fscanf()

char name[20];

int age;

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

fscanf(fp, "%s %d", name, &age);

printf("%s %d", name, age);

fclose(fp);

[Link] to a file

Methods

1.​ Character by character — fputc()


2.​ String by string — fputs()
3.​ Formatted data — fprintf()
4.​ Binary data — fwrite()

EXAMPLE:
FILE *fp = fopen("[Link]", "w");
fprintf(fp, "Name: Fatima\nAge: 20");
fclose(fp);

[Link] a file

Appending adds new data at the end of an existing file without erasing previous content.

SYNTAX:
FILE *fp = fopen("[Link]", "a");
fprintf(fp, "New line added!");
fclose(fp);

EXAMPLE:
FILE *fp = fopen("[Link]", "a");
fputs("Program executed successfully.\n", fp);
fclose(fp);
Function Purpose Example

fopen() Opens file fp = fopen("[Link]",


"r");

fclose( Closes file fclose(fp);


)

fgetc() Reads one character ch = fgetc(fp);

fprintf Writes formatted data fprintf(fp, "Hello");


()

fputs() Writes string fputs("Hi", fp);


FILE ACCESS METHODS

File access methods define how data is read from or written to a file. The two
main types are:

●​ Sequential Access
●​ Random(Direct) Access

1. SEQUENTIAL ACCESS TO FILES


Sequential access means accessing data in a file in a linear order, starting from the
beginning and proceeding step-by-step until the end.

⚙️ Working Principle
●​ File pointer starts at the beginning
●​ Data is read/written one element at a time
●​ Pointer automatically moves forward after each operation

📌 Example
File content:A B C D E

To read D, you must read:

A→B→C→D

🧰 Common Functions Used (C Language)


functions Purpose

fgetc() Read one character

fgets() Read one string


fputc() Write one character

fputs() Write a string

fprintf() Formatted output

fscanf() Formatted input

Example Program (Sequential Read)


#include <stdio.h>

int main() {

FILE *fp;

char ch;

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

if (fp == NULL) {

printf("File not found");

return 1;

while ((ch = fgetc(fp)) != EOF) {

printf("%c", ch);

fclose(fp);

return 0;

Advantages and Disadvantages of Sequential Access


Advantages Disadvantages

Simple to use Slow random access

Efficient for large files Time consuming for searching

Less memory usage Difficult to modify data

Good for streaming data No direct access

Faster for continuous reading/writing Inefficient for frequent updates

📌 Applications
●​ Text files
●​ Log files
●​ Reading configuration files

2. RANDOM (DIRECT) ACCESS TO FILES

Random access allows accessing any location directly in a file without reading previous
data.

⚙️ Working Principle
●​ Uses a file pointer to move to any position
●​ Position is specified using offset values
●​ Enables fast reading/writing

📌 Example
File:A B C D E

You can directly access D without reading A, B, C.

🧰 Important Functions
Function Purpose

fseek() Move file pointer

ftell() Get current position

rewind() Move pointer to beginning

📘 Syntax
fseek(file_pointer, offset, position);

🔸 Parameters:

●​ file_pointer → pointer to file


●​ offset → number of bytes to move
●​ position → reference point

🔸 Position Values:

●​ SEEK_SET → Beginning of file


●​ SEEK_CUR → Current position
●​ SEEK_END → End of file

💻 Example Program (Random Access)


#include <stdio.h>

int main() {
FILE *fp;
char ch;

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

if (fp == NULL) {
printf("File not found");
return 1; }
fseek(fp, 3, SEEK_SET); // Move to 4th character
ch = fgetc(fp);
printf("Character: %c", ch);

fclose(fp);
return 0;
}

💻 Example Using ftell()


#include <stdio.h>

int main() {
FILE *fp;

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

fseek(fp, 5, SEEK_SET);
printf("Position: %ld", ftell(fp));

fclose(fp);
return 0;
}

💻 Example Using rewind()

#include <stdio.h>

int main() {
FILE *fp;
char ch;

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

fseek(fp, 5, SEEK_SET);
rewind(fp); // back to start

ch = fgetc(fp);
printf("%c", ch);

fclose(fp);
return 0;
}

Advantages and Disadvantages


Advantages Disadvantages

Fast data access Complex implementations

Efficient searching More memory usage

Easy data modification Risk of data corruption

Saves time Not suitable for sequential processing

Suitable for large databases File structure dependency

📌 Applications
●​ Databases
●​ Binary files
●​ Large record systems
●​ File indexing systems

🔁 DIFFERENCE BETWEEN SEQUENTIAL & RANDOM ACCESS


Feature Sequential Access Random Access

Access type Linear Direct

Speed Slow for searching Fast

Complexity Simple complex

Functions fgetc(),fgets() fseek(),ftell()

Use case Text file Database

simple programs covering pointers and files

📘 1. Write data to a file using pointer


#include <stdio.h>

int main() {
FILE *fp;
char *str = "Hello Ruby"; // pointer to string
fp = fopen("[Link]", "w");

if (fp == NULL) {
printf("Error opening file");
return 1;
}

while (*str != '\0') {


fputc(*str, fp); // write character using pointer
str++;
}

fclose(fp);
return 0;
}

📘 2. Read file using pointer


#include <stdio.h>

int main() {

FILE *fp;

char ch;

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

if (fp == NULL) {

printf("File not found");

return 1;

char *ptr = &ch; // pointer to character


while (fscanf(fp, "%c", ptr) != EOF) {

printf("%c", *ptr);

fclose(fp);

return 0;

📘 3. Copy contents from one file to another (using pointers)


#include <stdio.h>

int main() {

FILE *fp1, *fp2;

char ch, *ptr;

fp1 = fopen("[Link]", "r");

fp2 = fopen("[Link]", "w");

if (fp1 == NULL || fp2 == NULL) {

printf("Error opening file");

return 1;

ptr = &ch;
while (fscanf(fp1, "%c", ptr) != EOF) {

fputc(*ptr, fp2);

fclose(fp1);

fclose(fp2);

return 0;

📘 4. Count characters in a file using pointer


#include <stdio.h>

int main() {
FILE *fp;
char ch, *ptr;
int count = 0;

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

if (fp == NULL) {
printf("File not found");
return 1;
}

ptr = &ch;

while (fscanf(fp, "%c", ptr) != EOF) {


count++;
}

printf("Total characters = %d", count);

fclose(fp);
return 0;
}
📘 5. Write array elements to file using pointer
#include <stdio.h>

int main() {
FILE *fp;
int arr[5] = {10, 20, 30, 40, 50};
int *ptr;

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

if (fp == NULL) {
printf("Error");
return 1;
}

ptr = arr; // pointer to array

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


fprintf(fp, "%d ", *(ptr + i));
}

fclose(fp);
return 0;
}

📘 6. Read array from file using pointer


#include <stdio.h>

int main() {

FILE *fp;

int arr[5], *ptr;


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

if (fp == NULL) {

printf("Error");

return 1;

ptr = arr;

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

fscanf(fp, "%d", (ptr + i));

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

printf("%d ", *(ptr + i));

fclose(fp);

return 0;

📘 7. Append data to a file using pointer


#include <stdio.h>

int main() {
FILE *fp;

char str[50], *ptr;

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

if (fp == NULL) {

printf("Error opening file");

return 1;

printf("Enter text: ");

gets(str); // simple input for exam

ptr = str;

while (*ptr != '\0') {

fputc(*ptr, fp);

ptr++;

fclose(fp);

return 0;

📘 8. Count vowels in a file using pointer


#include <stdio.h>

int main() {

FILE *fp;

char ch, *ptr;

int vowels = 0;

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

if (fp == NULL) {

printf("Error");

return 1;

ptr = &ch;

while (fscanf(fp, "%c", ptr) != EOF) {

if (*ptr=='a'||*ptr=='e'||*ptr=='i'||*ptr=='o'||*ptr=='u'||

*ptr=='A'||*ptr=='E'||*ptr=='I'||*ptr=='O'||*ptr=='U') {

vowels++;

printf("Vowels = %d", vowels);

fclose(fp);
return 0;

📘 9. Reverse contents of a file using pointer


#include <stdio.h>

int main() {
FILE *fp;
char ch;
long size;

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

if (fp == NULL) {
printf("Error");
return 1;
}

fseek(fp, 0, SEEK_END);
size = ftell(fp);

while (size--) {
fseek(fp, size, SEEK_SET);
ch = fgetc(fp);
printf("%c", ch);
}

fclose(fp);
return 0;
}

📘 10. Merge two files using pointer


#include <stdio.h>

int main() {

FILE *fp1, *fp2, *fp3;

char ch, *ptr;


fp1 = fopen("[Link]", "r");

fp2 = fopen("[Link]", "r");

fp3 = fopen("[Link]", "w");

if (fp1 == NULL || fp2 == NULL || fp3 == NULL) {

printf("Error");

return 1;

ptr = &ch;

while (fscanf(fp1, "%c", ptr) != EOF) {

fputc(*ptr, fp3);

while (fscanf(fp2, "%c", ptr) != EOF) {

fputc(*ptr, fp3);

fclose(fp1);

fclose(fp2);

fclose(fp3);

return 0;

You might also like