You are on page 1of 160

Programming for Problem

Solving II
For I B.Tech(AIML-B)-First Semester

Programming for Problem Solving II Unit I ppts 1


Programming for problem solving

Programming for Problem Solving II Unit I ppts 2


Programming for Problem Solving II Unit I ppts 3
Programming for Problem Solving II Unit I ppts 4
What is Structure
• Structure in c is a user-defined data type that enables us to store the
collection of different data types.

• Each element of a structure is called a member. Structures ca; simulate
the use of classes and templates as it can store various information.

• The ”struct” keyword is used to define the structure. Let's see the


syntax to define the structure in c.

Programming for Problem Solving II Unit I ppts 5


.

struct structure_name   
Let's see the example to define a
{   structure for an entity employee
    data_type member1;   in c.
    data_type member2;   struct employee  
    .   {   int id;  
    char name[20];  
    .  
    float salary;  
    data_type memeberN;   };
};  

Programming for Problem Solving II Unit I ppts 6


• Let's see the example to define a structure for an entity employee in c.
.

struct employee  
{   int id;  
    char name[20];  
    float salary;  
};

Programming for Problem Solving II Unit I ppts 7


The following image shows the memory allocation of the structure employee that is
defined in the above example.

Programming for Problem Solving II Unit I ppts 8


• Here, struct is the keyword; employee is the name of the
. structure; id, name, and salary are the members or fields of the
structure. Let's understand it by the diagram given below:

Programming for Problem Solving II Unit I ppts 9


Declaring structure variable

• we can declare a variable for the structure so that we can access the
member of the structure easily. There are two ways to declare structure
variable:
1.By struct keyword within main() function
2.By declaring a variable at the time of defining the structure.
• 1st way:
• Let's see the example to declare the structure variable by struct
keyword. It should be declared within the main function

Programming for Problem Solving II Unit I ppts 10


struct employee  
{   int id;  
..

    char name[50];  
    float salary;  
}; 
• Now write given code inside the main() function.
struct employee e1, e2; 
• The variables e1 and e2 can be used to access the values stored in the
structure. Here, e1 and e2 can be treated in the same way as the objects in 
C++ and Java.
• 2nd way:
• Let's see another way to declare variable at the time of defining the
structure.
Programming for Problem Solving II Unit I ppts 11
struct employee  
{   int id;  
.

    char name[50];  
    float salary;  
}e1,e2; 
Which approach is good
• If number of variables are not fixed, use the 1st approach. It provides
you the flexibility to declare the structure variable many times.

• If no. of variables are fixed, use 2nd approach. It saves your code to
declare a variable in main() function.

Programming for Problem Solving II Unit I ppts 12


.• Accessing members of the structure
• There are two ways to access structure members:
1.By . (member or dot operator)
2.By -> (structure pointer operator)
• Let's see the code to access the id member of p1 variable by ‘.’ (member)
operator.
p1.id
Let's see a simple example of structure in C language.  

Programming for Problem Solving II Unit I ppts 13


• Accessing the Structure Member with the Help of Pointers
.

• There are two ways to access the members of the structure with the help
of a structure pointer:

1.With the help of (*) asterisk or indirection operator and (.) dot operator.
2.With the help of ( -> ) Arrow operator.

• Below is the program to access the structure members using the


structure pointer with the help of the dot operator.

Programming for Problem Solving II Unit I ppts 14


// WAP to store and display id and name of employee using a structure
#include<stdio.h>  
.

#include <string.h>    
struct employee      
{   int id;      
    char name[50];      
}e1;  //declaring e1 variable for structure    
int main( )    
{     Output:
Employee1 id: 101
   //store first employee information     Employee1 name: sirname name
   e1.id=101;    

Programming for Problem Solving II Unit I ppts 15


   strcpy(e1.name, “sirname name");//copying string into char array    
   //printing first employee information    
   printf( "employee 1 id : %d\n", e1.id);    
   printf( "employee 1 name : %s\n", e1.name);    
return 0;  
}    

Programming for Problem Solving II Unit I ppts 16


Structure Pointer in C
• A structure pointer is defined as the pointer which points to the address of the memory
block that stores a structure known as the structure pointer.

• Complex data structures like Linked lists, trees, graphs, etc. are created with the help of
structure pointers.

• The structure pointer tells the address of a structure in memory by pointing the variable
to the structure variable.

Programming for Problem Solving II Unit I ppts 17


// C program to demonstrate structure pointer
.

#include <stdio.h>
 
struct point {
    int value;
};
 
int main()
{
     struct point s;
       // Initialization of the structure pointer
    struct point *ptr = &s;
     return 0;
}
} In the above code s is an instance of struct point and ptr is the struct pointer because it is storing the address of struct point.
Programming for Problem Solving II Unit I ppts 18
// WAP a C Program to demonstrate Structure pointer to the student
//record
#include <stdio.h>
.

#include <string.h>
 
struct Student {
    int roll_no;
    char name[30];
    char branch[40];
    int batch;
};

Programming for Problem Solving II Unit I ppts 19


int main()

    struct Student s1;
    struct Student *ptr = &s1;
 
    s1.roll_no = 27;
    strcpy(s1.name, “Krishna Anand");
    strcpy(s1.branch, "Computer Science And
Engineering");
    s1.batch = 2019;
Programming for Problem Solving II Unit I ppts 20
.

printf("Roll Number: %d\n", (*ptr).roll_no);


    printf("Name: %s\n", (*ptr).name);
    printf("Branch: %s\n", (*ptr).branch);
    printf("Batch: %d", (*ptr).batch);
 
    return 0;
}

Programming for Problem Solving II Unit I ppts 21


• Below is the program to access the structure members using the structure pointer with
the help of the Arrow operator. In this program, we have created a Structure Student
.

containing structure variable s. The Structure Student has roll_no, name, branch, and
batch.

// C Program to demonstrate Structure pointer


#i
// Creating Structure Student
struct Student {
    int roll_no;
    char name[30];
    char branch[40];
    int batch;
};

Programming for Problem Solving II Unit I ppts 22


struct Student s, *ptr;
 int . main()
{     ptr = &s;
// variable of structure with pointer defined
    // Taking inputs
    printf("Enter the Roll Number of Student\n");
    scanf("%d", &ptr->roll_no);

    printf("Enter Name of Student\n");


    scanf("%s", &ptr->name);
    printf("Enter Branch of Student\n");
    scanf("%s", &ptr->branch);
    printf("Enter batch of Student\n");
    scanf("%d", &ptr->batch);
    
 // Displaying details of the student
    printf("\nStudent details are: \n");
     printf("Roll No: %d\n", ptr->roll_no);
    printf("Name: %s\n", ptr->name);
    printf("Branch: %s\n", ptr->branch);
    printf("Batch: %d\n", ptr->batch);
     return 0; Programming for Problem Solving II Unit I ppts 23
}
Nested Structure in C
• C provides us the feature of nesting one structure within another
structure by using which, complex data types are created.

• For example, we may need to store the address of an entity employee in


a structure.

• The attribute address may also have the subparts as street number, city,
state, and pin code.
• Hence, to store the address of the employee, we need to store the
address of the employee into a separate structure and nest the structure
address into the structure employee. Consider the following program.
Programming for Problem Solving II Unit I ppts 24
#include<stdio.h>  
void main ()  
struct address   
.

{  
{       struct employee emp;  
    char city[20];       printf("Enter employee information?\n");  
    scanf("%s %s %d %s",emp.name, emp.add.city,  &emp.add.pin,
    int pin;  
    char phone[14];    emp.add.phone);  
};       printf("Printing the employee information....\n");  
    printf("name: %s\n City: %s\n Pincode: %d\n Phone: %s",
struct employee  
emp.name, emp.add.city, emp.add.pin, emp.add.phone);  
{   }  
    char name[20];  
    struct address add;  
};  
Programming for Problem Solving II Unit I ppts 25
WAP C program using the
concept of nested structure to
display student details which
again has the details of
concerned college.

Programming for Problem Solving II Unit I ppts 26


Q: Write a program to assign
name and price of a car using
structure.

Programming for Problem Solving II Unit I ppts 27


/*Accessing members of union using pointers-We can access the members of the union through
pointers by using the (->) arrow operator.*/
.

#include <stdio.h>  
union abc  
{  
    int a;  
    char b;  
};  
int main()  
{  
    union abc *ptr; // pointer variable declaration   In the above code, we have created a
    union abc var;   pointer variable, i.e., *ptr, that stores
    var.a= 90;   the address of var variable. Now, ptr
    ptr = &var;   can access the variable 'a' by using
    printf("The value of a is : %d", ptr->a);   the (->) operator. Hence the output of
    return 0;  
the above code would be 90.
Programming for Problem Solving II Unit I ppts 28
}  
Array of Structures in C
• An array of structres in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The
array of structures in C are used to store information about multiple entities of
different data types. The array of structures is also known as the collection of
structures

Programming for Problem Solving II Unit I ppts 29


Let's see an example of an array of structures that
stores information of 5 students and prints it.
#include<stdio.h>   printf("Enter Records of 5 
students");     printf("\
#include <string.h>     nStudent Information Li
for(i=0;i<5;i++){    
struct student{     printf("\nEnter Rollno:");     st:");    
int rollno;     scanf("%d",&st[i].rollno);     for(i=0;i<5;i++){    
printf("\nEnter Name:");     printf("\nRollno:
char name[10];     %d, Name:
scanf("%s",&st[i].name);    
};     }     %s",st[i].rollno,
int main(){     st[i].name);    
}    
int i;    
   return 0;    
struct student st[5];  }    
Programming for Problem Solving II Unit I ppts 30
Syntax of a function declaration taking structure as argument

Following is the function declaration syntax to accept structure variable as argument.


returnType functionName(struct tagName argName);

Example:
void displayDetail(struct student std);
In the above code we are declaring a function named displayDetail.

The return type of this function is set to void which means the function will return
no value.
In the list of parameters we have std of struct student type.
This means std is a variable of student structure.
So, the function displayDetail can take any variable of type student structure as argument.
Programming for Problem Solving II Unit I ppts 31
Passing structure variable to function
To pass a structure variable to a function all we have to do is write the name of the variable and
it will pass a copy of the structure variable.

In the following example code we are passing stdArr[i] variable of type 


student structure to the displayDetail function.

displayDetail(stdArr[i]);

Programming for Problem Solving II Unit I ppts 32


EXAMPLE PROGRAM – PASSING STRUCTURE TO
FUNCTION IN C BY VALUE:

• In this program, the whole structure is passed to another function by


value. It means the whole structure is passed to another function with
all members and their values. So, this structure can be accessed from
called function. This concept is very useful while writing very big
programs in C.

Programming for Problem Solving II Unit I ppts 33


#include <stdio.h> /*WAP to pass structure to a function*/ NOTE: Remember
#include <string.h> 1.Function declaration
 struct student 2.Function calling
{  func(record); 3.Function implementation
            int id;             return 0; 4.How to call fields of
            char name[20]; } structure using struct var?
            float percentage;
void func(struct student record)
};
{
 void func(struct student record);
printf(" Id is: %d \n", record.id);
 int main() printf(" Name is: %s \n", record.name);
{    printf(" Percentage is: %f \n", record.percentage);
            struct student record; }
             record.id=1;
            strcpy(record.name, "Raju");
            record.percentage = 86.5;
              Programming for Problem Solving II Unit I ppts 34
.

• EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN


C BY ADDRESS(PASSING STRUCTURE TO FUNCTION BY CALL
REFERENCE):
• In this program, the whole structure is passed to another function by address.

• It means only the address of the structure is passed to another function. The
whole structure is not passed to another function with all members and their
values.

• So, this structure can be accessed from called function by its address.

Programming for Problem Solving II Unit I ppts 35


#include <stdio.h> func(&record);
#include <string.h>           return 0;
}
..

 struct student
{  
           int id; void func(struct student *record)
{
           char name[20];
 printf(" Id is: %d \n", record->id);
           float percentage;
 printf(" Name is: %s \n", record->name);
};
printf(" Percentage is: %f \n", record->percentage);
 void func(struct student *record); }
 int main()
{
          struct student record;
           record.id=1;
          strcpy(record.name, "Raju");
          record.percentage = 86.5;

Programming for Problem Solving II Unit I ppts 36


Passing Structure Members as arguments to Function

• We can pass individual members to a function just like ordinary variables.


• The following program demonstrates how to pass structure members as arguments to
the function.

Function
declaration

Programming for Problem Solving II Unit I ppts 37


NOTE:
1.Function
declaration
2.Function
calling
3. Function
implementation
4.How to pass ,
access and
display structure
values from
function

Programming for Problem Solving II Unit I ppts 38


Passing Structure Pointers as Argument to a Function 
• Although passing structure variable as an argument allows us to pass all
the members of the structure to a function there are some downsides to
this operation.

1.Recall that a copy of the structure is passed to the formal argument. If the
structure is large and you are passing structure variables frequently then
it can take quite a bit of time which make the program inefficient.

2.Additional memory is required to save every copy of the structure.


• The following program demonstrates how to pass structure pointers as
arguments to a function

Programming for Problem Solving II Unit I ppts 39


NOTE : how to declare pointer
variable to the structure inside
function and how pass address of
variable to function through which
we are able to access members of
structure.

Step1: normal declaration of variable 2. pass address of this


normal
Programming for Problem variable
Solving II Unit I ppts 3. receive as pointer variable in implementation
40
. NOTE:How to
receive the address
of instance variable
by using the pointer
varible inside the
implementation of
function and how to
print the values

Programming for Problem Solving II Unit I ppts 41


Array of Structures as Function Arguments
.

• We have already seen how to pass an array of integers to a function.


Similarly, we can pass an array of structures to a function.

• The following program demonstrates how we can pass an array of


structures to a function.

Programming for Problem Solving II Unit I ppts 42


Passing Array of Structures as Function Arguments

//PPS abbreviation is Price per stock


//Price per stock
Signature for array of structure

Programming for Problem Solving II Unit I ppts 43


Programming for Problem Solving II Unit I ppts 44
How it works: ( just go to the code don’t check the line numbers because they may not match)

In lines 7-13, a structure company is declared with four members namely 


.

name, ceo, revenue, pps.

In line 15, the prototype of function print_struct() is declared which accepts an


argument of type array of structures.

In lines 20-24, an array of structure called companies of type struct company


 is declared and initialized.

In line 25, print_struct() is called along with argument companies.


Since the name of the array is a constant pointer to the 0th element of the array,
the formal argument of print_struct() is assigned the address of variable companies.

So now str_arr is pointing to the original array of structure, any changes made


inside the function will affect the original structure. If you don't want to call a
function to modify the original structure use the keyword const.
Programming for Problem Solving II Unit I ppts 45
.
In line 32, variable i is declared to control the for loop.

In lines 34-41, a for loop is used to loops through the array of structure and
prints the details of each company.

The control then passes to the main() function and the function terminates

Programming for Problem Solving II Unit I ppts 46


typedef in C
• The typedef is a keyword used in C programming to provide some meaningful
names to the already existing variable in the C program.
• It behaves similarly as we define the alias for the commands. In short, we can say
that this keyword is used to redefine the name of an already existing variable.
• Syntax of typedef
1.typedef <existing_name> <alias_name>  
• In the above syntax, 'existing_name' is the name of an already existing variable
while 'alias name' is another name given to the existing variable.

• For example, suppose we want to create a variable of type unsigned int, then it


becomes a tedious task if we want to declare multiple variables of this type. To
overcome the problem, we use a typedef keyword

Programming for Problem Solving II Unit I ppts 47


typedef unsigned int unit;  
• In the above statements, we have declared the unit variable of type unsigned int by
.

using a typedef keyword.
• Now, we can create the variables of type unsigned int by writing the following
statement:
Existing name ,and alias name

unit a, b;   
• instead of writing:
unsigned int a, b;  

Till now, we have observed that the typedef keyword provides a nice shortcut by


providing an alternative name for an already existing variable.

Advantage: This keyword is useful when we are dealing with the long data type
especially, structure declarations Programming for Problem Solving II Unit I ppts 48
//WAP using typedef

#include <stdio.h>  
int main()  
{  
typedef unsigned int unit;  //here we tell to compiler that unit is type of deftype of variable.
unit i,j;  // here i,j are unit type of variable means partially we tell that these are integers
i=10;  
j=20;  
printf("Value of i is :%d",i);  
printf("\nValue of j is :%d",j);  
return 0;  
}  

Programming for Problem Solving II Unit I ppts 49


• Using typedef with pointers
• We can also provide another name or alias name to the pointer variables with the help
.

of the typedef.
• For example, we normally declare a pointer, as shown below:
Int *ptr;  
• We can rename the above pointer variable as given below:
typedef int *ptr;  
• In the above statement, we have declared the variable of type int*. Now, we can
create the variable of type int* by simply using the 'ptr' variable as shown in the
below statement:
ptr p1, p2 ;  
• In the above statement, p1 and p2 are the variables of type 'ptr'.

Programming for Problem Solving II Unit I ppts 50


Enumerated type declaration

• As we know that in C language, we need to declare the variable of a pre-defined type


such as int, float, char, etc.

• Similarly, we can declare the variable of a user-defined data type, such as enum.
Let's see how we can declare the variable of an enum type.

• In the below code, we create an enum type named as weekdays, and it contains the
name of all the seven days. We have assigned 1 value to the Sunday, and all other
names will be given a value as the previous value plus one.

Programming for Problem Solving II Unit I ppts 51


//WAP using enumeration OR enum

#include <stdio.h>  
.

 enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, S
aturday};  
 int main()  
{  
 enum weekdays w; // variable declaration of weekdays type  
 w=Monday; // assigning value of Monday to w.  
 printf("The value of w is %d",w);  
w=Saturday;
printf("The value of w is %d",w);  
    return 0;  
}  
Programming for Problem Solving II Unit I ppts 52
Why do we use enum?

• The enum is used when we want our variable to have only a set of values.

• The enum is also used in a switch case statement in which we pass the enum
variable in a switch parenthesis. It ensures that the value of the case block should be
defined in an enum

Programming for Problem Solving II Unit I ppts 53


• The enum in C is also known as the enumerated type. It is a user-defined data type
that consists of integer values, and it provides meaningful names to these values.
.

• The use of enum in C makes the program easy to understand and maintain. The
enum is defined by using the enum keyword.
• The following is the way to define the enum in C:

enum flag{integer_const1, integer_const2,.....integter_constN};  

• In the above declaration, we define the enum named as flag containing 'N' integer
constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on.
We can also change the default value of the integer constants at the time of the
declaration.

Programming for Problem Solving II Unit I ppts 54


Enumerated type declaration

• As we know that in C language, we need to declare the variable of a pre-defined


type such as int, float, char, etc. Similarly, we can declare the variable of a user-
defined data type, such as enum. Let's see how we can declare the variable of an
enum type.
• Suppose we create the enum of type status as shown below:
enum status{false,true};  

Programming for Problem Solving II Unit I ppts 55


• Now, we create the variable of status type:
.

enum status s; // creating a variable of the status type.  
• In the above statement, we have declared the 's' variable of type status.

• To create a variable, the above two statements can be written as:


enum status{false,true} s;  

• In this case, the default value of false will be equal to 0, and the value of true will be
equal to 1.

Programming for Problem Solving II Unit I ppts 56


UNIT II -pointer in C language
• The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function,
or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2
byte.
• Consider the following example to define a pointer which stores the
address of an integer.

Programming for Problem Solving II Unit I ppts 57


int n = 10;   
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer
.

A) Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.
int *a;//pointer to int  
char *c;//pointer to char 
Pointer Example
An example of using pointers to print the address and value is given below.

Programming for Problem Solving II Unit I ppts 58


Declaration of different pointers
int *ip; /* pointer to an integer */

double *dp; /* pointer to a double */

float *fp; /* pointer to a float */

char *ch /* pointer to a character */

Programming for Problem Solving II Unit I ppts 59


.

• As you can see in the above figure, pointer variable stores the address
of number variable, i.e., fff4. The value of number variable is 50. But
the address of pointer variable p is aaa3.

• By the help of * (indirection operator), we can print the value of


pointer variable p.

Programming for Problem Solving II Unit I ppts 60


.

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used


to retrieving strings, trees, etc. and used with arrays, structures, and
functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's


memory.

Programming for Problem Solving II Unit I ppts 61


Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation


In c language, we can dynamically allocate memory using malloc() and
calloc() functions where the pointer is used.

2) Arrays, Functions, and Structures


Pointers in c language are widely used in arrays, functions, and
structures. It reduces the code and improves the performance.

Programming for Problem Solving II Unit I ppts 62


// WAP to print the address of two variables of any type

#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %u\n", &var1 );
printf("Address of var2 variable: %u\n", &var2 );
return 0;
}

Programming for Problem Solving II Unit I ppts 63


//WAP to increment value of a variable using pointer

#include <stdio.h>
int x = 0; //Declaration of normal variable
void main()
{
int *ptr = &x; //assigning address of normal variable to pointer
printf("%p\n", ptr);
x++; // incrementing the variable value using increment operator
printf("%p\n ", ptr);
}

Programming for Problem Solving II Unit I ppts 64


Arrays and Pointers

Pointer

•The pointer is an Address of a variable in memory.



•It allows us to indirectly access variables.

•in other words, we can talk about its address rather than its value

Programming for Problem Solving II Unit I ppts 65


Arrays and Pointers
• Let's assume that the first element of the array scores
has the address 1200.
• This means that
• &nums[0] would be 1000 (we stored value in that location
1200). Since an int occupies 4 bytes, the ad1204dress of the
second element of the array, &nums[1] would be, the address of
the third element of the array, &nums[2] would be 1208, and so
on

Programming for Problem Solving II Unit I ppts 66


What about a two-dimensional array declared like this?

int nums [2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}};

Visualize the said two-dimensional array as a table of rows and columns:

  [0] [1] [2] [3]


nums 54 6 23 45
  1200 1204 1208 1212

Programming for Problem Solving II Unit I ppts 67


Programming for Problem Solving II Unit I ppts 68
Programming for Problem Solving II Unit I ppts 69
Second
operation
with pointer

First
operation
with pointer

Programming for Problem Solving II Unit I ppts 70


//Access Array Elements Using Pointers
#include <stdio.h>
int main()
{
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
Programming for Problem Solving II Unit I ppts 71
Explanation for the above program
In this program, the elements are stored in the integer array data[].
Then, the elements of the array are accessed using the pointer notation.
By the way,
•data[0] is equivalent to *data and &data[0] is equivalent to data
•data[1] is equivalent to *(data + 1) and &data[1] is equivalent to data + 1
•data[2] is equivalent to *(data + 2) and &data[2] is equivalent to data + 2
•...
•data[i] is equivalent to *(data + i) and &data[i] is equivalent to data + i

Programming for Problem Solving II Unit I ppts 72


/*WAP using Arrays and Pointers*/

Programming for Problem Solving II Unit I ppts 73


/*AIM: WAP to store and print 6 values using a pointer type
of variable within the for loop*/

Programming for Problem Solving II Unit I ppts 74


Pointer to Pointer (C Double Pointer)

• As we know that, a pointer is used to store the address of a variable in


C. Pointer reduces the access time of a variable. However, In C, we
can also define a pointer to store the address of another pointer. Such
pointer is known as a double pointer (pointer to pointer). The first
pointer is used to store the address of a variable whereas the second
pointer is used to store the address of the first pointer. Let's understand
it by the diagram given below.

• The syntax of declaring a double pointer is given below.


int **p; // pointer to a pointer which is pointing to an integer.
Programming for Problem Solving II Unit I ppts 75
Programming for Problem Solving II Unit I ppts 76
/*WAP using double pointer*/
#include<stdio.h>  
.
void main ()  
{  
    int a = 10;  
    int *p;  
    int **pp;   
    p = &a; // pointer p is pointing to the address of a  
    pp = &p; // pointer pp is a double pointer pointing to the address of pointer p  
    printf("address of a: %x\n",p); // Address of a will be printed   
    printf("address of p: %x\n",pp); // Address of p will be printed  
    printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will 
//be printed  
    printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the poin //
ter stoyred at pp  
}  
Programming for Problem Solving II Unit I ppts 77
Programming for Problem Solving II Unit I ppts 78
Relationship between Pointers and Arrays in C
Let an array representation as shown below :

Programming for Problem Solving II Unit I ppts 79


Relationship between Pointers and Arrays in C
.

• Let an array representation as shown below (From previous figure OR in general the following
are true about arrays and pointers)

1. With respect to the concept of the pointer, let us see some important points related to arrays
in general :
2. 'arr' serves two purposes here, first it is the name of the array and second, arr itself
represents the base address of the array i.e. 300300 in the above case, if we print the
value in arr then it will print the address of the first element in the array.
3. As the array name arr itself represents the base address of the array, then by
default arr acts as a pointer to the first element of the array.

4. arr is the same as &arr and &arr[0] in C Language.


5. If we use dereferencing operator (*) on any of the above representations of array address,
we will get the value of the very first element of the array.

Programming for Problem Solving II Unit I ppts 80


#include <stdio.h>
int main() /* write a program to assign 5 values ,and print their
{ addresses values and stored number values*/
// array declaration and initialization Pointer5.c
int arr[5] = {3, 5, 7, 9, 11};

/* printing the addresses and values represented by


arr, &arr and &arr[0] */
All statements
produces
printf("arr : %u, Value : %d\n", arr, *arr);
All statements gives the same results
same result

printf("&arr : %u, Value : %d\n", &arr, *(arr));


printf("&arr[0]:%u,Value : %d\n", &arr[0],
*( &arr[0]));
return 0;
}
Programming for Problem Solving II Unit I ppts
output of previous program
[Success] Your code was executed successfully

arr : 63744176, Value : 3

&arr : 63744176, Value : 3

&arr[0] : 63744176, Value : 3

Programming for Problem Solving II Unit I ppts 82


Explanation Previous program
• Note : Output address will be different at every run.

• You can run and check your code here.

• We can see that arr, &arr and &arr[0] are printing the same addresses and


values in the output window.
• So, it is clear from the above program and output
that arr, &arr and &arr[0] represent the same address in the system's memory.

Programming for Problem Solving II Unit I ppts 83


#include <stdio.h>
int main()
{ /*WAP to store 5 values in an
// array declaration and initialization array and display index location,
int arr[5] = {2, 4, 6, 8, 10}, i; addresses and value stored in
that 5 locations using pointers*/
for(i = 0; i < 5; i++)
{

// printing the elements address and value at // arr[i] //using *(arr + i) syntax

printf("[index %d] Address : %u, Value : %d\n", i, (arr + i), *(arr + i));
}
return 0;
}

Programming for Problem Solving II Unit I ppts 84


output.

OUTPUT :
[Success] Your code was executed successfully
[index 0] Address : 2364420656, Value : 2
[index 1] Address : 2364420660, Value : 4
[index 2] Address : 2364420664, Value : 6
[index 3] Address : 2364420668, Value : 8
[index 4] Address : 2364420672, Value : 10

Programming for Problem Solving II Unit I ppts 85


Syntax Representing Array in Terms of Pointers in C
In a C Program, we denote array elements as arr[i], where i is the index value.

Below is a similar syntax in terms of pointers of how we can represent the array


elements using the dereferencing operator (*) on the array name i.e. using the
pointers property of the array.

1. *(arr + i)

2. * is a dereferencing operator used to extract the value from the address (arr + i).

3. *(arr + i) is the same as arr[i] in a C Program.

arr represents the array name and i represents the index value.

Programming for Problem Solving II Unit I ppts 86


Dynamic memory allocation in C

Programming for Problem Solving II Unit I ppts 87


Programming for Problem Solving II Unit I ppts 88
Programming for Problem Solving II Unit I ppts 89
/*WAP using malloc
function/dynamic memory
allocation OR WAP to perform
Pointer Arithmetic operations*/
Pointer4.c

Programming for Problem Solving II Unit I ppts 90


Programming for Problem Solving II Unit I ppts 91
.

calloc() function in C
• The calloc() function allocates multiple block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
• The syntax of calloc() function is given below:

Programming for Problem Solving II Unit I ppts 92


Programming for Problem Solving II Unit I ppts 93
  printf("Sorry! unable to allocate memory");    
        exit(0);    
.

    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    //sum=sum+*(ptr+i)
    }    
    printf("Sum=%d",sum);    
    free(ptr);    
return 0;  
}    
Programming for Problem Solving II Unit I ppts 94
.

realloc() function in C
• If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
• Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)  

free() function in C
• The memory occupied by malloc() or calloc() functions must be released by calling
free() function. Otherwise, it will consume memory until program exit.
• Let's see the syntax of free() function.
free(ptr)  

Programming for Problem Solving II Unit I ppts 95


Programming for Problem Solving II Unit I ppts 96
/*WAP to find sum upto a given maximum value*/

#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));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
Programming for Problem Solving II Unit I ppts 97
 printf("Enter elements of array: ");    
.

    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}  

Programming for Problem Solving II Unit I ppts 98


.

Enter elements of array: 3 Enter elements of array: 10 10 10 Sum=30

Programming for Problem Solving II Unit I ppts 99


// WAP using malloc() and free() functions

Programming for Problem Solving II Unit I ppts 100


.

Programming for Problem Solving II Unit I ppts 101


.

Programming for Problem Solving II Unit I ppts 102


Programming for Problem Solving II Unit I ppts 103
.

Programming for Problem Solving II Unit I ppts 104


Arrays of pointers (to strings)
.

Array of pointers is an array whose elements are pointers to the base address of the
string.
It is declared and initialized as follows −
char *a[4 ] = {"one", "two", "three“,”Four”};
/*Here, a[0] is a ptr to the base add of the string "one" */
/*a[1] is a ptr to the base add of the string "two“*/
/*a[2] is a ptr to the base add of the string "three“*/

Advantages
•Unlink the two-dimensional array of characters. In (array of strings), in array of
pointers to strings there is no fixed memory size for storage.

•The strings occupy as many bytes as required hence, there is no wastage of


space
Programming for Problem Solving II Unit I ppts 105
/*WAP to implement the concept of points to strings*/
#include<stdio.h>
.

int main() {
// jth character of string str[i] can be
// storing multiple strings using pointer // accessed from the location str[i]+j
char *str[4] = { while (*(str[i] + j) != '\0') {
"String", printf("%c", *(str[i]+j));
"Topics", j++;
}
"Hello",
// print a new line after printing the ith
"World" string
}; printf("\n");
int i = 0; }
for (i = 0; i < 4; i++) return 0;
}
{
int j = 0;
Programming for Problem Solving II Unit I ppts 106
Programming for Problem Solving II Unit I ppts 107
Programming for Problem Solving II Unit I ppts 108
.In the above example, we use char type pointer variable str of size 4 to store four
strings with variable sizes.
Unlike a 2-D array, we don't have to define the column size at the time of
variable declaration, which saves us unnecessary wastage of
memory. str[i] stored the starting address of ith string in the array.

Subsequent characters of the string can be evaluated by incrementing on the


base address i.e. str[i] + j has the address of jth character of ith string. To get the
value of ith string, we increment base address of ith string str[i] till we encounter
a null character (indicating string termination) using a while loop.

Programming for Problem Solving II Unit I ppts 109


.•
Instead of using arrays, we can use character pointers to store a
string value.
• To store multiple strings, we can use a 2D array or a pointer
variable. Using a 2D array leads to memory wastage because the
size of the columns is fixed for every row in a 2D array in C. This can
be overcome using pointers.

Programming for Problem Solving II Unit I ppts 110


WAP using pointer to 2Dimension strings

Programming for Problem Solving II Unit I ppts 111


Programming for Problem Solving II Unit I ppts 112
/*declaring array of pointers to  string at compile time    */
#include<stdio.h>
Void main ()
.

{
   char *a[5] = {“one”, “two”, “three”, “four”, “five”}; /*Write any 5 names here*/

int i;  
 printf ( “The assigned strings are:”)  
 for (i=0; i<5; i++)  
  printf (“%s”, a[i]); //printing array of strings  
 getch ();
}

OUTPUT

The strings are: one two three four five


Programming for Problem Solving II Unit I ppts 113
Storage for Strings in C

• In C, a string can be referred to either using a character pointer or as a


character array. 
• Strings as character arrays
char str[4] = "GfG"; /*One extra for string terminator*/

/*    OR    */

char str[4] = {‘G’, ‘f’, ‘G’, '\0’};

/* '\0' is string terminator */

Programming for Problem Solving II Unit I ppts 114


• When strings are declared as character arrays, they are stored like other
.

types of arrays in C.
• For example, if str[] is an auto variable then the string is stored in stack
segment, if it’s a global or static variable then stored in data segment,
etc.
Strings using character pointers 
Using character pointer strings can be stored in two ways:
1) Read only string in a shared segment. 
• When a string value is directly assigned to a pointer, in most of the
compilers, it’s stored in a read-only block (generally in data segment)
that is shared among functions. 
char *str  =  "GfG"; 

Programming for Problem Solving II Unit I ppts 115


In the above line “GfG” is stored in a shared read-only location,
.

but pointer str is stored in read-write memory.

You can change str to point something else but cannot change value at present
str. So this kind of string should only be used when we don’t want to modify
the string at a later stage in the program.

2) Dynamically allocated in heap segment. 

Strings are stored like other dynamically allocated things in C and can be
shared among functions. 

Programming for Problem Solving II Unit I ppts 116


C – Pointer to Pointer (Double Pointer)

• We already know that a pointer points to a location in memory and is


thus used to store the address of variables. So, when we define a
pointer to a pointer. The first pointer is used to store the address of the
variable. And the second pointer is used to store the address of the first
pointer. That is why they are also known as double-pointers.

• We can use a pointer to a pointer to change the values of normal


pointers or create a variable-sized 2-D array. A double pointer
occupies the same amount of space in the memory stack as a normal
pointer.

Programming for Problem Solving II Unit I ppts 117


.
How to Declare a Pointer to a Pointer in C?

Declaring Pointer to Pointer is similar to declaring a pointer in C.


The difference is we have to place an additional ‘*’ before the name of the pointer. 

Syntax:
data_type_of_pointer **name_of_variable = & normal_pointer_variable;

Programming for Problem Solving II Unit I ppts 118


Example pointer to pointer or double pointer
• Example:

int val = 5;

int *ptr = &val; // storing address of val to pointer ptr.

int **d_ptr = &ptr; // pointer to a pointer declared

// which is pointing to an integer.


The below diagram explains the concept of Double Pointers: 

Programming for Problem Solving II Unit I ppts 119


.

Programming for Problem Solving II Unit I ppts 120


.
The above diagram shows the memory representation of a pointer to a
pointer. The first pointer ptr1 stores the address of the variable and the
second pointer ptr2 stores the address of the first pointer. 

Programming for Problem Solving II Unit I ppts 121


Programming for Problem Solving II Unit I ppts 122
Programming for Problem Solving II Unit I ppts 123
.

Programming for Problem Solving II Unit I ppts 124


What will be the size of a pointer to a pointer in C?
In the C programming language double pointer behave similarly to a normal pointer in C.
.
So, the size of the double-pointer variable and the size of the normal pointer variable is
always equal. 
// C program to demonstrate sizeof normal and double pointer.
#include <stdio.h>
Output
  
Size of normal Pointer: 8
int main()
Size of Double Pointer: 8
{
  
    int a = 5;
    int* ptr = &a;
    int** d_ptr = &ptr;
  
    printf(" Size of normal Pointer: %d \n", sizeof(ptr));
    printf(" Size of Double Pointer: %d \n", sizeof(d_ptr));
  
    return 0; Programming for Problem Solving II Unit I ppts 125
UNIT-III File Handling in C
• In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.

• However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.

• File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed
on a file.

Programming for Problem Solving II Unit I ppts 126


Why Do We Need File Handling in C?
• There are times when the output generated out of a program after its compilation and running
do not serve our intended purpose. In such cases, we might want to check the program’s
output various times. Now, compiling and running the very same program multiple times
becomes a tedious task for any programmer. It is exactly where file handling becomes useful.
• Let us look at a few reasons why file handling makes programming easier for all:
• Reusability: File handling allows us to preserve the information/data generated after we run
the program.
• Saves Time: Some programs might require a large amount of input from their users. In such
cases, file handling allows you to easily access a part of a code using individual commands.
• Commendable storage capacity: When storing data in files, you can leave behind the worry
of storing all the info in bulk in any program.
• Portability: The contents available in any file can be transferred to another one without any
data loss in the computer system. This saves a lot of effort and minimises the risk of flawed
coding.

Programming for Problem Solving II Unit I ppts 127


Types of Files in a C Program
• When referring to file handling, we refer to files in the form of data files. Now, these data
files are available in 2 distinct forms in the C language, namely:
• Text Files
• Binary Files
1. Text Files
• The text files are the most basic/simplest types of files that a user can create in a C
program. We create the text files using an extension .txt with the help of a simple text
editor. In general, we can use notepads for the creation of .txt files. These files store info
internally in ASCII character format, but when we open these files, the content/text opens
in a human-readable form.
• Text files are, thus, very easy to access as well as use. But there’s one major
disadvantage; it lacks security. Since a .txt file can be accessed easily, information isn’t
very secure in it. Added to this, text files consume a very large space in storage.
• To solve these problems, we have a different type of file in C programs, known as binary
files Programming for Problem Solving II Unit I ppts 128
2.Binary Files
.

• The binary files store info and data in the binary format of 0’s and 1’s (the
binary number system). Thus, the files occupy comparatively lesser space in
the storage. In simpler words, the binary files store data and info the same
way a computer holds the info in its memory. Thus, it can be accessed very
easily as compared to a text file.

• The binary files are created with the extension .bin in a program, and it
overcomes the drawback of the text files in a program since humans can’t
read it; only machines can. Thus, the information becomes much more
secure. Thus, binary files are safest in terms of storing data files in a C
program

Programming for Problem Solving II Unit I ppts 129


How to Create a File
Whenever you want to work with a file, the first step is to create a file.
A file is nothing but space in a memory where data is stored.
To create a file in a ‘C’ program following syntax is used,
FILE *fp; fp = fopen ("file_name", "mode");

• In the above syntax, the file is a data structure which is defined in the standard
library.
• fopen is a standard function which is used to open a file.
• If the file is not present on the system, then it is created and then opened.
• If a file is already present on the system, then it is directly opened using this
function.
• fp is a file pointer which points to the type file.

• Whenever you open or create a file, you have to specify what you are going to do
with the file. A file in ‘C’ programming can be created or opened for reading/writing
purposes. A mode is used to specify whether you want to open a file for any of the
purposes
Programming for Problem Solving II Unit I ppts 130
How to Close a file

One should always close a file whenever the operations on file are over.
.

It means the contents and links to the file are terminated. This prevents accidental
damage to the file.

‘C’ provides the fclose function to perform file closing operation. The syntax of fclose is
as follows,

fclose (file_pointer);

Example:
FILE *fp;
fp = fopen ("data.txt", "r"); …..

fclose (fp);
Programming for Problem Solving II Unit I ppts 131
Writing to a File
• In C, when you write to a file, newline characters ‘\n’ must be explicitly
added.
• The stdio library offers the necessary functions to write to a file:
• fputc(char, file_pointer): It writes a character to the file pointed to by
file_pointer.
• fputs(str, file_pointer): It writes a string to the file pointed to by
file_pointer.
• fprintf(file_pointer, str, variable_lists): It prints a string to the file
pointed to by file_pointer. The string can optionally include format
specifiers and a list of variables variable_lists.
• The program below shows how to perform writing to a file

Programming for Problem Solving II Unit I ppts 132


//using fputc() Function:

.
#include <stdio.h>
int main()
{
int i; FILE * fptr;
char fn[50];
char str[] = “our students Rocks\n";
fptr = fopen(“Raju.txt", "w");
// "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++) {
/* write to file using fputc() function */
fputc(str[i],fptr);
}
fclose(fptr);
return 0;
}
Programming for Problem Solving II Unit I ppts 133
//using fputs
#include <stdio.h> int main()
{
FILE * fp;
fp = fopen("fputs_test.txt", "w+");

fputs("This is demo on fputs,", fp);

fputs("We don't need to use for loop\n", fp);

fputs("Easier than fputc function\n", fp);

fclose(fp);
return (0);
}
Programming for Problem Solving II Unit I ppts 134
//Using fprintf()Function:
.

#include <stdio.h>
int main()
{ FILE *fptr;
fptr = fopen("fprintf_test.txt", "w");
/* write to file */
fprintf (fptr, "Learning C with faculty\n");
fclose(fptr);
return 0;
}

Programming for Problem Solving II Unit I ppts 135


Operators/Functions that We Use for File Handling in C

We can use a variety of functions in order to open a file, read it, write more data, create a
new file, close or delete a file, search for a file, etc. These are known as file handling
operators in C.
Here’s a list of functions that allow you to do so:

Description of Function Function in Use


• used to open an existing file or a new fopen()
file
• writing data into an available file fprintf()
• reading the data available in a file fscanf()
• writing any character into the fputc()
program file
• reading the character from an fgetc()
available file

Programming for Problem Solving II Unit I ppts 136


• used to close the program file fclose()
.

• used to set the file pointer to fseek()


the intended file position

• writing an integer into an fputw()


available file
• used to read an integer from fgetw()
the given file

• used for reading the current ftell()


position of a file

• sets an intended file pointer to rewind()


the file’s beginning itself

Programming for Problem Solving II Unit I ppts 137


Operations Done in File Handling
• File handling in C enables us to create, update, read, and delete the files
.

stored on the local file system through our C program. The following
operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file
Functions for file handling
• There are many functions in the C library to open, read, write, search and
close the file. A list of file functions are given below:
Programming for Problem Solving II Unit I ppts 138
Programming for Problem Solving II Unit I ppts 139
Programming for Problem Solving II Unit I ppts 140
Programming for Problem Solving II Unit I ppts 141
Programming for Problem Solving II Unit I ppts 142
Programming for Problem Solving II Unit I ppts 143
Programming for Problem Solving II Unit I ppts 144
Programming for Problem Solving II Unit I ppts 145
• Closing File: fclose()
.

• The fclose() function is used to close a file. The file must be closed after
performing all the operations on it. The syntax of fclose() function is
given below:
int fclose( FILE *fp );  

Programming for Problem Solving II Unit I ppts 146


//Input/Output operation on File

..

#include<stdio.h>
fp = fopen("one.txt", "r");
int main()
{ while( (ch = getc(fp)! = EOF)
FILE *fp; printf("%c",ch);
char ch;
// closing the file pointer
fp = fopen("one.txt", "w");
fclose(fp);
printf("Enter data...");
while( (ch = getchar()) != EOF) { return 0;
putc(ch, fp); }
}
fclose(fp);

Programming for Problem Solving II Unit I ppts 147


Reading and Writing to File using fprintf() and fscanf()

#include<stdio.h>
struct emp do
{ char name[10]; {
int age; fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
};
}
void main() while(!feof(q));
{ struct emp e; }
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
Programming for Problem Solving II Unit I ppts 148
fclose(p);
In this program, we have created two FILE pointers and both are refering to the same
file but in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which
can then be printed on the console using standard printf() function.

Programming for Problem Solving II Unit I ppts 149


fseek() ftell() rewind() functions
,   and   

.
•fseek(): It is used to move the reading control to different positions using fseek function.

•ftell(): It tells the byte location of current position of cursor in file pointer.

•rewind(): It moves the control to beginning of the file.

Programming for Problem Solving II Unit I ppts 150


Programming for Problem Solving II Unit I ppts 151
Reading data from a File
• There are three different functions dedicated to reading data from a file
.

• fgetc(file_pointer): It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is sent back.

• fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string
in a buffer in which the NULL character ‘\0’ is appended as the last character.

• fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and


analyze data. It reads characters from the file and assigns the input to a list of variable
pointers variable_adresses using conversion specifiers. Keep in mind that as with scanf,
fscanf stops reading a string when space or newline is encountered.

Programming for Problem Solving II Unit I ppts 152


The following program demonstrates reading from fputs_test.txt file using
fgets(),fscanf() and fgetc () functions respectively :

#include <stdio.h> int main() {


FILE * file_pointer; char buffer[30], c;
file_pointer = fopen("fprintf_test.txt", "r");
printf("----read a line----\n");
fgets(buffer, 50, file_pointer);
printf("%s\n", buffer);
printf("----read and parse data----\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
char str1[10], str2[2], str3[20], str4[2];
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);

Programming for Problem Solving II Unit I ppts 153


.

printf("Read String1 |%s|\n", str1);


printf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read String4 |%s|\n", str4);
printf("----read the entire file----\n");

file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer

while ((c = getc(file_pointer)) != EOF)


printf("%c", c); fclose(file_pointer); return 0; }

Programming for Problem Solving II Unit I ppts 154


.

Result:
----read a line---- Learning C with Guru99
----read and parse data----
Read String1 |Learning| Read String2 |C|
Read String3 |with| Read String4 |Guru99|
----read the entire file---- Learning C with Guru99

Programming for Problem Solving II Unit I ppts 155


1.In the above program, we have opened the file called “fprintf_test.txt” which was
.previously written using fprintf() function, and it contains “Learning C with
Guru99” string. We read it using the fgets() function which reads line by line where
the buffer size must be enough to handle the entire line.

2.We reopen the file to reset the pointer file to point at the beginning of the file. Create
various strings variables to handle each word separately. Print the variables to see
their contents. The fscanf() is mainly used to extract and parse data from a file.

3.Reopen the file to reset the pointer file to point at the beginning of the file. Read
data and print it from the file character by character using getc() function until the
EOF statement is encountered

4.After performing a reading operation file using different variants, we again closed
the file using the fclose function.

Programming for Problem Solving II Unit I ppts 156


.
• Interactive File Read and Write with getc and putc

• These are the simplest file operations. Getc stands for get character,
and putc stands for put character. These two functions are used to
handle only a single character at a time.
• Following program demonstrates the file handling functions in ‘C’
programming:

Programming for Problem Solving II Unit I ppts 157


.
#include <stdio.h> int main()
{
FILE * fp; char c;
printf("File Handling\n");
//open a file fp = fopen("demo.txt", "w");
//writing operation
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
//close file fclose(fp);

Programming for Problem Solving II Unit I ppts 158


.
printf("Data Entered:\n");
//reading fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF)
{
printf("%c", c); }
fclose(fp); return 0;
}

Programming for Problem Solving II Unit I ppts 159


.
1.In the above program we have created and opened a file called
demo in a write mode.
2.After a write operation is performed, then the file is closed using the
fclose function.
3.We have again opened a file which now contains data in a reading
mode. A while loop will execute until the eof is found. Once the end
of file is found the operation will be terminated and data will be
displayed using printf function.
4.After performing a reading operation file is again closed using the
fclose function.
Programming for Problem Solving II Unit I ppts 160

You might also like