Professional Documents
Culture Documents
Solving II
For I B.Tech(AIML-B)-First Semester
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; };
};
struct employee
{ int id;
char name[20];
float salary;
};
• 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
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.
• 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.
#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;
• 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.
#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;
};
containing structure variable s. The Structure Student has roll_no, name, branch, and
batch.
• 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.
#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
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.
displayDetail(stdArr[i]);
• 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.
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;
Function
declaration
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.
name, ceo, revenue, pps.
In lines 34-41, a for loop is used to loops through the array of structure and
prints the details of each company.
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;
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;
}
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'.
• 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.
#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
• 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.
enum status s; // creating a variable of the status type.
• In the above statement, we have declared the 's' variable of type status.
• In this case, the default value of false will be equal to 0, and the value of true will be
equal to 1.
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.
• 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.
Advantage of pointer
#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;
}
#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);
}
Pointer
•in other words, we can talk about its address rather than its value
First
operation
with pointer
• 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.
// 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;
}
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
1. *(arr + i)
2. * is a dereferencing operator used to extract the value from the address (arr + i).
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:
}
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)
#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;
}
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.
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.
{
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
/* OR */
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";
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.
Strings are stored like other dynamically allocated things in C and can be
shared among functions.
Syntax:
data_type_of_pointer **name_of_variable = & normal_pointer_variable;
int val = 5;
• 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.
• 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
• 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
.
#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+");
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;
}
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:
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 );
..
#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);
#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.
.
•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.
• 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.
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
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.
• 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: