Programming For Problem Solving Handwritten Notes
Programming For Problem Solving Handwritten Notes
Page 6
Page 7
Page 8
Page 9
Page 10
Page 11
Page 12
Page 13
Page 14
Page 15
Page 16
Page 17
Page 18
Page 19
Page 20
Page 21
Page 22
Page 23
Page 24
Page 25
Page 26
Page 27
Page 28
Page 29
Page 30
Page 31
Page 32
Page 33
Page 34
Page 35
Page 1
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
Page 8
Page 9
Page 10
Page 11
Page 12
Page 13
\
Unit -V
Pointer & File Handling
5.1 Pointer:
C programming tasks are performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers. Every variable is a memory
location and every memory location has its address defined which can be accessed using
ampersand (&) operator, which denotes an address in memory.
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
Output:
printf("Address of var2 variable: %x\n", &var2 ); Address of var1 variable: bff5a400
return 0;
Address of var2 variable: bff5a3f6
}
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using it
to store any variable address
type *var-name;
here type is the pointer's base type
The asterisk * used to declare a pointer
var-name is the name of the pointer variable
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
printf("Address stored in ip variable: %x\n", ip );
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
Output
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
5.1.2 NULL Pointers: It is always a good practice to assign a NULL value to a pointer
variable in case you do not have an exact address to be assigned. This is done at the time of
variable declaration. A pointer that is assigned NULL is called a null pointer.
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0.
Examples
int a = 5, *p = &a;
float b = 2.2, *pf = &b;
char c = 'x', *pc= &c;
Suppose the address of variables a, b and c are 1000, 4000 ,5000 respectively, so initially
values of
pI, p2, p3 will be 1000, 4000 and 5000.
i. malloc()
ii. calloc()
iii. realloc()
iv. free()
Static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while memory can be increased while executing program.
executing program.
Syntax of malloc()
ii. C calloc()
The name "calloc" stands for contiguous allocation. The malloc() function allocates memory
and leaves the memory uninitialized. Whereas, the calloc() function allocates memory and
initializes all bits to zero.
Syntax of calloc()
The above statement allocates contiguous space in memory for 25 elements of type floatC
iii. free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on
their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
iv. C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change
the size of previously allocated memory using the realloc() function.
Syntax of realloc()
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int)); Output
printf("Addresses of previously allocated memory: "); Enter size: 2
for(i = 0; i < n1; ++i) Addresses of previously allocated
printf("%u\n",ptr + i); memory:26855472
printf("\nEnter the new size: "); 26855476
scanf("%d", &n2);
// rellocating the memory Enter the new size: 4
ptr = realloc(ptr, n2 * sizeof(int)); Addresses of newly allocated
printf("Addresses of newly allocated memory: "); memory:26855472
for(i = 0; i < n2; ++i) 26855476
printf("%u\n", ptr + i); 26855480
free(ptr); 26855484
return 0;
}
5.2 Use of pointers in self-referential structures
Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
i. Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the
objects of a self-referential structure with the single link and access the corresponding
data members. The connection formed is shown in the following figure.
ii. Self Referential Structure with Multiple Links: Self referential structures with
multiple links can have more than one self-pointers. Many complicated data structures
can be easily constructed using these structures. Such structures can easily connect to
more than one nodes at a time. The following example shows one such structure with
more than one links.
//Program to understand Self Referential Structures
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30; Output:
ob2.data2 = 40; 30
// Linking ob1 and ob2
40
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
5.2.2 Linked List
Linked List can be defined as collection of objects called nodes that are randomly stored in
the memory.A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory. The last node of the list
contains pointer to the null.
• The list is not required to be contiguously present in the memory. The node can reside
any where in the memory and linked together to make a list. This achieves optimized
utilization of space.
• list size is limited to the memory size and doesn't need to be declared in advance.
• Empty node can not be present in the linked list.
• We can store values of primitive types or objects in the singly linked list.
Till now, we were using array data structure to organize the group of elements that are to be
stored individually in the memory. However, Array has several advantages and disadvantages
which must be known in order to decide the data structure which will be used throughout the
program.
• The size of array must be known in advance before using it in the program.
• Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
• All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.
5.3. File management
A File can be used to store a large volume of persistent data. Like many other
languages 'C' provides following file management functions,
function purpose
fopen () Creating a file or opening an existing file
The fopen() function is used to create a new file or open an existing file in C.The fopen
function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
FILE *ptr;
ptr = fopen(“file_name”, “mode”)
Eg.
ptr=fopen("E:\\cprogram\\newprogram.txt","w");
ptr=fopen("E:\\cprogram\\oldprogram.bin","rb");
Opening Modes in Standard I/O
Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary mode. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
a Open for append. If the file does not exist, it will be created.
Data is added to the end of the file.
ab Open for append in binary mode. If the file does not exist, it will be created.
Data is added to the end of the file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
rb+ Open for both reading and writing in If the file does not exist, fopen() returns NULL.
binary mode.
w+ Open for both reading and writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb+ Open for both reading and writing in If the file exists, its contents are overwritten.
binary mode. If the file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exist, it will be created.
ab+ Open for both reading and appending If the file does not exist, it will be created.
in binary mode.
The file (both text and binary) should be closed after reading/writing. Closing a file is
performed using the fclose() function.
fclose(ptr);
Output
Inserts a particular header using #include: These directives tell the CPP to get stdio.h from
System Libraries and add the text to the current source file. The next line tells CPP toget
myheader.h from the local directory and add the content to the current source file.
#include <stdio.h>
#include "myheader.h"
Output:
Added value:10 arithmetic.c
Multiplied value:25
BYE!See you Soon
#undef
The #undef preprocessor directive is used to undefine the constant or macro defined by
#define.
#include <stdio.h>
#define PI 3.14
#undef PI
main() {
printf("%f",PI);
}
Output:
#ifdef , #else and #endif : The #ifdef preprocessor directive checks if macro is defined by
#define. If yes, it executes the code otherwise #else code is executed, if present. The #else
preprocessor directive evaluates the expression or condition if condition of #if is false. It can
be used with #if, #elif, #ifdef and #ifndef directives.
getch(); getch();
} }
Output:
Output:
Enter a:5
2 Value of a: 5
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
Value of a: 5
#if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.
#include <stdio.h>
#include <conio.h>
#define NUMBER 0
void main() {
#if (NUMBER==0)
printf("Value of Number is: %d",NUMBER);
#endif
getch();
}
Output:
www.universityacademy.in
#error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
#include<stdio.h>
#ifndef MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
Output:
Compile Time Error: First include then compile
5.5 Command Line Argument in C
Command line argument is a parameter supplied to the program when it is invoked. It is
mostly used when you need to control your program from outside. Command line arguments
are passed to the main() method.
Syntax:
main() function of a C program accepts arguments from command line or from other shell
scripts by following commands. They are,
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the
following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the
following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces
the following result.
$./a.out
One argument expected
#include <stdio.h>
#include <stdlib.h>
return 0;
}
OUTPUT: