0% found this document useful (0 votes)
120 views154 pages

Programming For Problem Solving Handwritten Notes

Uploaded by

momag28913
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
120 views154 pages

Programming For Problem Solving Handwritten Notes

Uploaded by

momag28913
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 154

Page 5

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

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
5.1.1 How to Use Pointers?
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in 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.

5.1.3 Pointer Arithmetic


All types of arithmetic operations are not possible with pointers. The only valid operations
that can be performed are as
i. Addition of an integer to a pointer and increment operation.
ii. Subtraction of an integer from a pointer and decrement operation
iii. Subtraction of a pointer from another pointer of same type.
Pointer arithmetic is somewhat different from ordinary arithmetic. Here all arithmetic is
performed relative to the size of base type of pointer. For example, if we have an integer
poier pi which contains address
⚫ 1000 then on incrementing we get 1002 instead of 1001. This is because the size of
int data type is 2.
⚫ Similarly on decrementing pi, we will get 998 instead of 999.
⚫ The expression (pi+3) will represent the address 1006.

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.

Dynamic memory allocation in C

The concept of dynamic memory allocation in c language enables the C programmer to


allocate memory at runtime. Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.

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.

used in array. used in linked list.


i. C malloc()
The name "malloc" stands for memory allocation. The malloc() function reserves a block of
memory of the specified number of bytes. And, it returns a pointer of void which can be
casted into pointers of any form.

Syntax of malloc()

ptr = (castType*) malloc(size);


Example
ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory.

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

ptr = (castType*)calloc(n, size);


Example:
ptr = (float*) calloc(25, sizeof(float));

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.

Example 1: malloc() and free()


// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{ Output:
printf("Error! memory not allocated."); Enter number of elements: 5
exit(0); Enter elements: 4
3
}
5
printf("Enter elements: ");
8
for(i = 0; i < n; ++i) 9
{ Sum = 29
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);

// deallocating the memory


free(ptr);
return 0;
}

Example 2: calloc() and free()


// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n); Output:
ptr = (int*) calloc(n, sizeof(int)); Enter number of elements: 5
if(ptr == NULL) Enter elements: 4
{ 5
printf("Error! memory not allocated."); 8
exit(0); 9
} 2
Sum = 28
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

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

ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size x.

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.

5.2.1 Types of Self Referential Structures

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.

Uses of Linked List

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

Why use linked list over array?

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,

i. Creating a new file


ii. Opening an existing file
iii. Closing a file
iv. Reading from and writing information to a file

functions available in 'C

function purpose
fopen () Creating a file or opening an existing file

fclose () Closing a file


fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

5.3.1 Creating or opening file using fopen()

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.

5.3.2 Closing a File

The file (both text and binary) should be closed after reading/writing. Closing a file is
performed using the fclose() function.

fclose(ptr);

Here, ptr is a file pointer associated with the file to be closed.


5.3.3 Reading and writing to a text file For reading and writing to a text file, we use the
functions fprintf() and fscanf(). They are just the file versions of printf() and scanf(). The
only difference is that fprint() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
// use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{ Output
printf("Error!");
Enter num: 2
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

Example 2: Read from a text file


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1); Output
}
fscanf(fptr,"%d", &num); Value of n=2
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
/*Write a C program to read numbers from a file and write even, odd and prime numbers in
separate files.*/
#include <stdio.h>
void main() {
FILE *fp1, *fp2, *fp3, *fp4;
int n, i, num, flag = 0;

/* open data.txt in read mode */


fp1 = fopen("C:\\data.txt", "w");
printf("Enter the value for n:");
scanf("%d", &n);
for (i = 0; i <= n; i++)
fprintf(fp1, "%d ", i);
fprintf(fp1, "\n");
fclose(fp1);

/* open files to write even, odd and prime nos separately */


fp1 = fopen("C:\\data.txt", "r");
fp2 = fopen("C:\\even.txt", "w");
fp3 = fopen("C:\\odd.txt", "w");
fp4 = fopen("C:\\prime.txt", "w");

fprintf(fp2, "Even Numbers:\n");


fprintf(fp3, "Odd Numbers:\n");
fprintf(fp4, "Prime Numbers:\n");

/* print even, odd and prime numbers in separate files */


while (!feof(fp1)) {
fscanf(fp1, "%d", &num);
if (num % 2 == 0) {
fprintf(fp2, "%d ", num);
} else {
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (!flag) {
fprintf(fp4, "%d ", num);
}
}
fprintf(fp3, "%d ", num);
flag = 0;
}
}
fprintf(fp2, "\n");
fprintf(fp3, "\n");
fprintf(fp4, "\n");

/* close all opened files */


fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
}

Output

Enter the value for n:20


5.4 C Preprocessor and Macros
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. All preprocessor commands begin with
a hash symbol (#).

5.4.1 Important preprocessor directives

Sr.No. Directive & Description


i. #define Substitutes a preprocessor macro.

ii. #include Inserts a particular header from another file.

iii. #undef Undefines a preprocessor macro.

iv. #ifdef Returns true if this macro is defined.

v. #ifndef Returns true if this macro is not defined.

vi. #if Tests if a compile time condition is true.

vii. #else The alternative for #if.


viii. #elif #else and #if in one statement.

ix. #endif Ends preprocessor conditional.


x. #error Prints error message on stderr.
Macros using #define : A macro is a fragment of code that is given a name. You can define
a macro in C using the #define preprocessor directive.

Example 1: #define preprocessor


#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}

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"

// Creating your own header file and using it accordingly.

void add(int a, int b) #include <stdio.h>


{ #include "myhead.h"
int main()
printf("Added value=%d\n", a + b);
{
} add(4, 6);
void multiply(int a, int b) /*This calls add function written in myhead.h
{ and therefore no compilation error.*/
printf("Multiplied value=%d\n", a * multiply(5, 5);
b);
// Same for the multiply function in myhead.h
} printf("BYE!See you Soon");
myhead.h return 0;
}

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:

Compile Time Error: 'PI' undeclared

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

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


#include <conio.h> #include <conio.h>
#define NOINPUT void main() {
void main() { int a=0;
int a=0; #ifdef NOINPUT
#ifdef NOINPUT a=2;
a=2; #else
#else printf("Enter a:");
printf("Enter a:"); scanf("%d", &a);
scanf("%d", &a); #endif
#endif
printf("Value of a: %d\n", a); printf("Value of a: %d\n", a);

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:

Value of Number is: 0

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:

int main(int argc, char *argv[])

main() function of a C program accepts arguments from command line or from other shell
scripts by following commands. They are,

argc – Number of arguments in the command line including program name

argv[] – This is carrying all the arguments

#include <stdio.h>

int main( int argc, char *argv[] ) {

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>

int main(int argc, char *argv[]) // command line arguments


{
if(argc!=5)
{
printf("Arguments passed through command line not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);

return 0;
}

Save this program as test.c


we run the executable “test” along with 4 arguments in command line like below.

$./a.out this is a program

OUTPUT:

Program name : test


1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Important Questions

1. What do you mean by pointer arithmetic?


2. What is dynamic memory allocation? Explain the calloc(), malloc(), ealloc() and free()
functions in detail. What is lifetime of a variable,which is created dynamically?
3. Explain the importance of pointers in C. Write a program in C to swap the values of two
numbers entered by user using function call by reference method
4. Write macro definition with arguments for calculation of simple interest and amount. Store
these macro definitions in a file called 'interest.h'. Include this file in your program and use
the macro definitions for calculating simple interest and amount.
5. What are different file opening modes? Write a program in C that reads a series of integer
numbers from a file named INPUT and write all odd numbers to a file to be called ODD and
all even numbers to a file to be called EVEN.
6. Write a short note on following pre-processor directives with example:
a. Macro Expansion
b. File Inclusion
7. Explain command line arguments in C with the help of example.
8. Define various file operations in C. Write a program in C to count and print the number of
characters in a file.

You might also like