Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PSPC Unit 4 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

UNIT IV STRUCTURES
Structure - Nested structures – Pointer and Structures – Array of structures –
Example Program using structures and pointers – Self referential structures –
Dynamic memory allocation - Singly linked list - typedef.

STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures
Collection of similar data types. Collection of different data types.
Static memory allocation is done in arrays Dynamic memory allocation is done in structures.
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to
an array element. access members of structures
Array is a pointer to its first element. Structure is not a pointer.
Array is a derived data type. Structure is a user defined data type.
Accessing array element takes less time Accessing structure member takes more time.
It has no keywords. It uses keyword “struct”
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
struct tag_name struct student
{ {
datatype member 1; char name[10];
datatype member 2; int roll_no;
datatype member n; float percentage;
}; };

Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.

1
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

2. Declaring structure variable


Syntax: Example:
struct tag_name
{ struct student
datatype member 1; {
datatype member 2; char name[10];
datatype member 3; int roll_no;
float percentage;
}
struct book s1,s2;
datatype member n;
} variable1, variable2,……. variable n; Note:
Structure variable can be declared within the
structure definition or in the main function.

3.Initializing the members of structure:


Initialization can be done in 2 ways.
 Compile time initialization:
- uses assignment operator(=) to initialize values to the members of structure.
Example:
struct student s1={“ramya”,1001,45.8};
struct student s2={“anitha”,1002,89.6};
 Run time initialization:
- uses scanf function to read the input from the user.
Example:
printf("enter s1 student details");
scanf("%s%d%f",s1.name,&s1.roll_no,&s1.percentage);
printf("enter s2 student details");
scanf("%s%d%f",s2.name,&s2.roll_no,&s2.percentage);

4. Accessing the members of the structure:


- Members can be accessed using .operator (dot). Also pointer operator is used(->)
Syntax:
structure_variable_name . member_name;
Example:
s1.name // to access name of s1
s2.percentage // to access percentage of s2

2
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

Program to print student details( accessing member Output:


using .dot operator): Enter rollno, name , percentage
#include<stdio.h> 1001
struct student ramya
{ 96.8
int roll; Student details are:
char name[10]; ROLL_NO=1001
float percentage; NAME=ramya
}s1; PERCENTAGE=96.80000
int main()
{
printf("Enter rollno, name , percentage\n");
scanf("%d%s%f", &s1.roll, s1.name, &s1.percentage);
printf("Student details are:\n");
printf ("ROLL_NO=%d\n NAME=%s\n
PERCENTAGE=%f\n", s1.roll, s1.name, s1.percentage);
return(0);
}

NESTED STRUCTURE:
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.

Syntax:
Example:
structure tagname_1
struct Employee
{
{
data_type member1;
char ename[20];
data_type member2;
int empid;
data_type member3;
int salary;
..
struct date
member n;
{
structure tagname_2
int day;
{
int month;
data_type member_1;
int year;
data_type member_2;
}doj;
data_type member_3;
... }emp;
member_n;
} var1;
} var2;

3
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

Syntax:

outerstructurevariable . innerstructure variable . innerstructuremember

To Access the Nested members,

Accessing month Field : emp1.doj.month

Accessing day Field : emp1.doj.day

Accessing year Field : emp1.doj.year

Program to display employee details using nested Output:


structure:
#include <stdio.h> Employee Name : ramya
struct Employee
{ Employee ID : 1001
char ename[20];
int empid; Employee Salary : 25000
int salary;
Employee DOJ : 25/9/1988
struct date
{
int day;
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee
emp={"ramya",1001,25000,{25,9,1988}};
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee ID : %d",emp.empid);
printf("\nEmployee Salary : %d",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.day,
emp.doj.month, emp.doj.year);
return 0;
}

4
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

ARRAY OF STRUCTURES:

- Array of structures is nothing but collection of structures.


- Declaring an array of structure is same as declaring an array of fundamental types.
- This is also called as structure array in c.

- Here s is an array of 5 elements where each element is of type struct student.


- We can use s to store 5 structure variables of type struct student.
- To access individual elements we will use subscript notation ([]) and to access the
members of each element we will use dot (.) operator as usual.

Accessing members of array structure:


s[0] : points to the 0th element of the array.
s[1] : points to the 1st element of the array.

s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.

Program to print 5 student details using array of Output:


structures:
#include<stdio.h> Enter details of student 1
#define MAX 5 Enter name: ravi
struct student Enter roll no: 1005
{ Enter marks: 89.6
char name[20];
int roll_no, i; Enter details of student 2
float marks; Enter name: priya
}; Enter roll no: 1002
int main() Enter marks: 89.6

5
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

{
struct student s[5]; Enter details of student 3
int i; Enter name: mahesh
for(i = 0; i < MAX; i++) Enter roll no: 1003
{ Enter marks: 56.9
printf("\n Enter details of student %d\n\n", i+1);
Enter details of student 4
printf("Enter name: "); Enter name: rini
scanf("%s", s[i].name); Enter roll no: 1004
Enter marks: 96
printf("Enter roll no: ");
scanf("%d", &s[i].roll_no); Enter details of student 5
Enter name: ram
printf("Enter marks: "); Enter roll no: 1005
scanf("%f", &s[i].marks); Enter marks: 36.9
}

printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.

How To Find the Size of Structure?


- sizeof() function is used to find the size of structure.
- sizeof can be applied to any data-type, including primitive types such as integer and floating-
point types, pointer types, or compound datatypes such as Structure, union etc.Syntax:
Example: (Sizeof() for structure)
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
};
int main()

6
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

{
printf("Size of book structure is :%d",sizeof(b1.bookname));
}
Output:
Size of book structure is :84

POINTER AND STRUCTURE:


C structure can be accessed in 2 ways in a C program. They are,
(i) Using normal structure variable
(ii) Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and
Arrow (->) is used to access the data using pointer variable.
Syntax: Example:
struct name struct product
{ {
member1; int prod_id;
member2; char prod_name[20];
. float price;
}; };
struct name *ptr; struct product *p1;

Difference between normal structure variable and pointer variable:

7
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable declaration

8
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

struct book *ptr; // pointer variable declaration


ptr=&b1; // pointer variable initialization
printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\n");
scanf("%s",ptr->bookname);
printf("enter author\n");
scanf("%s",&ptr->author);
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr-
>author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000

DYNAMIC MEMORY ALLOCATION:


Why do we need to go for Dynamic Memory Allocation?
 We know, an array is uses static memory allocation technique because, the size of the
array is fixed. So we cannot increase or decrease the size of the array once size is
declared.
 Hence, the array we declared may be insufficient or sometimes size may be more than
what we required.
 To solve this issue, we can allocate memory dynamically.
Dynamic Memory Allocation:
 The process of allocating memory during program execution is called dynamic
memory allocation.
 It allows us to manually handle memory space for our program.
There are 4 library functions defined under <stdlib.h> which can be used for dynamic
memory allocation.
They are,

9
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

malloc()
calloc()
realloc()
free()

(i)malloc() function:
- malloc() stands for "memory allocation".
- malloc () function is used to allocate space in memory during the execution of the
program.
- This function reserves a block of memory of the given size and returns a pointer of
type void (that is to be typecasted)

Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor.
Hence given, sizeof() function irrespective of 2 byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage
value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");

10
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning

(ii)calloc() function:
 The name calloc() stands for "contiguous allocation".(continues)
 calloc() is another memory allocation function that is used for allocating memory at
runtime.
 This statement will allocate contiguous space in memory for an array of n elements.
 The only difference between malloc() and calloc() is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same
size
 calloc () initializes the allocated memory to zero. But, malloc() does not.
 If it fails to allocate enough space as specified, it returns a NULL pointer.

Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of
float( i.e, 4 bytes)

Program: (To copy a string to allocated memory using calloc() ):


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;

11
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

ptr = (char*)calloc( 20,sizeof(char) ); // memory is allocated dynamically


if( ptr== NULL)
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning

(iii) realloc():
- realloc() used to change the memory size that is already allocated using malloc()
and calloc() functions.

Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x

Difference between malloc() and calloc():

12
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

free()
- free() to release the space that are allocated using memory by malloc (), calloc (),
realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x

Program: ( To copy a string to allocated memory using realloc())


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char *)malloc( 20 * sizeof(char) ); //memory is allocated dynamically
if( ptr == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content : %s\n", ptr );
ptr=realloc(ptr,100*sizeof(char));
strcpy( ptr,"can store 100 characters");
printf("Resized memory : %s\n", ptr);
free(ptr);
}

Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters

13
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

C Program to generate Salary Slip of employee( Dynamic memory allocation for


Structure using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
int i,n; Enter Others1000
struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct Enter IT1000
employee)); enter the nameraja
for(i=0;i<n;i++) Enter Basic Salary (RS): 25000
{
printf("enter the name"); Enter Hra1000
scanf("%s",(ptr+i)->name);
printf("Enter Basic Salary (RS): "); Enter da1000
scanf("%d",&(ptr+i)->basic);
printf("\nEnter Hra"); Enter TA1000
scanf("%d",&(ptr+i)->hra);
printf("\nEnter da"); Enter Others500
scanf("%d",&(ptr+i)->da);
printf("\n Enter TA"); Enter pf1000
scanf("%d",&(ptr+i)->ta);
printf("\nEnter Others"); Enter IT1500
scanf("%d",&(ptr+i)->others);
printf("\nEnter pf"); Name is ravi Net Salary
scanf("%d",&(ptr+i)->pf); is:RS 13500
printf("\nEnter IT");
scanf("%d",&(ptr+i)->it); Name is raja Net Salary
is:RS 26000
//calculate net salary

14
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da +


(ptr+i)->hra + (ptr+i)->ta + (ptr+i)->others - ((ptr+i)-
>pf+(ptr+i)->it);
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)-
>net_salary);
}
return(0);
}

SELF REFERENTIAL STRUCTURES:

A structure that contains at least one pointers to a structure as its member along with other
members is known as self-referential structure.

Pointer variable declaration in structure Self-referential structure declaration


struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;

The above illustrated self referential structure prototype describes one node that comprises of
two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element
is present.
Several such inter-connected nodes create a chain of structures(Linked List).

 A self-referential structure can dynamically be expanded or contracted.


 Operations like insertion or deletion of nodes in a self- referential structure involve
simple and straight forward alteration of pointers.

15
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

Singly Linked List(Linear List):


In linked list, elements are not stored at contiguous location; the elements are linked
using pointers.
A linked list is represented by a pointer to the first node of the linked list.
The first node is called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1) data
2) pointer to the next node
In C, we can represent a node using structures.
Below is an example of a linked list node with an integer data.
Operations on Linked List:
1. Inserting a node in linked list:
A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
i) Insertion at the front of linked list:
When a new node is added at the front, it becomes the header of the list. Here, Node E is
added at the front. Hence E becomes the header node and not A.

ii) Inserting node at a given position

iii) Inserting at the End

16
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

2. Deleting a node:
If node to be deleted is root, simply delete it.
To delete a middle node, we must have pointer to the node previous to the node to be
deleted. So if positions is not zero, we run a loop position-1 times and get pointer to the
previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from
the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.

Program to insert, delete and display the elements in Output:


singly linked list
Program : enter the number of nodes
#include<stdio.h> 4
#include<stdlib.h> Enter the element
#define NULL 0 10
typedef struct list enter the element20
{ enter the element30
int no; enter the element40
struct list *next; enter ur option=
}LIST; 1.insert 2.delete
LIST *p,*t,*h,*y,*ptr,*pt; 3.display 4.exit
void create(void); 3
void insert(void); List elements are:
void delet(void); 10 20 30 40
void display(void); Enter your option
int j,pos,k=1;count; 1
void main() enter the element to be
{ inserted
int n,i=1,opt; 35
printf("%d",sizeof(LIST)); enter the position to insert
printf("enter the number of nodes\n"); 4
scanf("%d",&n);
count=n; Enter your option
while(i<=n) 3
{ List elements are:

17
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

create(); 10 20 30 35
i++; 40
} Enter your option
printf("enter ur option=\n"); 2
printf("1.insert\t 2.delete \t 3.display\t 4.exit\n"); enter the position to delete:
do 2
{
scanf("%d",&opt); Enter your option
switch(opt) 3
{ List elements are:
case 1: 10 30 35 40
insert(); Enter your option
count++; 4
break;
case 2:
delet();
count--;
if(count==0)
{
printf("\n List empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option\n");
}while(opt!=4);
}
void create()
{
if(p==NULL)
{
p=(LIST*)malloc(sizeof(LIST));
printf("Enter the element\n");
scanf("%d",&p->no);
p->next=NULL;
h=p;

18
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

}
else
{
t=(LIST*)malloc(sizeof(LIST));
printf("enter the element");
scanf("%d",&t->no);
t->next=NULL;
p->next=t;
p=t;
}
}

void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++){
t=t->next;
}
p->next=t->next;
t->next=p;
t=p;
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);

19
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

if(pos==1)
{
h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++){
t=t->next;
}
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}

TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;

Example: (Use of typedef on integer data type)


 - In this program, Intdata is
Program:
#include<stdio.h> an user defined name or alias
typedef int Intdata; // Intdata is alias name name for an integer data type.
of int
 - All properties of the integer

20
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

int main() will be applied on Intdata also.


{
int a=10;  - Integerdata is an alias name
Intdata b=20; to existing user defined name
typedef Intdata Integerdata; // Integerdata is again called Intdata.
alias name of Intdata
Integerdata s;
s=a+b;
printf("\n Sum:= %d",s);
return(0);
}
Output:
Sum:=30

Use of typedef on structure datatype:


 Output:
Program:
#include<stdio.h>  enter the name
typedef struct telephone
 anitha
{
char name[20];  enter the telephone number
int tel_no;  3216546531
}t1;
 Name:anitha
int main()
{  telephone number :909193779
t1 t11;
printf("enter the name");
scanf("%s",t11.name);
printf("enter the telephone number");
scanf("%s",&t11.tel_no);
printf("Name:%s\n",t11.name);
printf("telephone number is:%d",t11.tel_no);
return(0);
}

Example Programs Using Pointer and Structure:

1. C program to read, display, add, and subtract two Output


distances. Distance must bedefined using kms and
meters using structures.(typedef)

21
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
{ 2. Display the distances
3. Add the distances
int kms; 4. Subtract the distances
int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
DISTANCE subtract_distance(DISTANCE,DISTANCE); Enter the first distance in kms
DISTANCE dl, d2, d3, d4; and metres:
3
320
int main()
{ Enter the second distancekms
int option; and metres:
do 5
{ 100
printf("\n ***MAIN MENU***");
***MAIN MENU***
printf ("\n 1. Read the distances ");
1. Read the distances
printf ("\n 2. Display the distances"); 2. Display the distances
printf ("\n 3. Add the distances "); 3. Add the distances
printf ("\n 4. Subtract the distances"); 4. Subtract the distances
printf ("\n 5. EXIT"); 5. EXIT
printf ("\n Enter your option: "); Enter your option: 2
scanf("%d", &option);
The first distance is: 3 kms
switch(option) 320 metres
{ The second distance is: 5 kms
case 1: 100 metres
printf("\n Enter the first distance in kms and metres: ***MAIN MENU***
"); 1. Read the distances
scanf ("%d %d", &dl .kms, &dl .metres); 2. Display the distances
3. Add the distances
printf("\n Enter the second distancekms and metres:
4. Subtract the distances
"); 5. EXIT
scanf ("%d %d" , &d2 .kms, &d2 .metres); Enter your option: 3
break;
case 2: The sum of two distances is: 8
printf("\n The first distance is: %d kms %d metres " kms 420 metres
, dl.kms, dl.metres); ***MAIN MENU***
1. Read the distances
printf("\n The second distance is: %d kms %d
2. Display the distances
metres " , d2 .kms, d2 .metres); 3. Add the distances

22
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

break; 4. Subtract the distances


case 3: 5. EXIT
d3 = add_distance(dl, d2); Enter your option: 4
printf("\n The sum of two distances is: %d kms %d
The difference between two
metres", d3.kms, d3.metres); distances is: 1 kms 780 metres
break; ***MAIN MENU***
case 4: 1. Read the distances
d4 = subtract_distance(dl, d2); 2. Display the distances
printf("\n The difference between two distances is: 3. Add the distances
%d kms %d metres ", d4.kms, d4 .metres); 4. Subtract the distances
5. EXIT
break;
Enter your option: 5
}
}
while(option != 5);
{
return 0;
}
}
DISTANCE add_distance(DISTANCE dl, DISTANCE d2)
{
DISTANCE sum;
sum.metres = dl.metres + d2. metres;
sum.kms = dl.kms + d2.kms;
if(sum.metres >= 1000)
{
sum.metres = sum.metres%1000;
sum.kms += 1;
}
return sum;
}
DISTANCE subtract_distance(DISTANCE dl,DISTANCE
d2)
{
DISTANCE sub;
if(dl.kms > d2.kms)
{
sub.metres = dl.metres - d2. metres;
sub.kms = dl.kms - d2.kms;
}

23
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

else
{
sub.metres = d2.metres - dl. metres;
sub.kms = d2.kms - dl.kms;
}
if(sub.metres < 0)
{
sub.kms = sub.kms - 1;
sub.metres = sub.metres + 1000;
}
return sub;
}

2.C program to add, subtract two complex numbers using


Output
structure.
Program: Press 1 to add two complex
#include <stdio.h> numbers
#include <stdlib.h> Press 2 to subtract two complex
struct complex numbers
{ Press 3 to exit
int real, img; Enter your choice
}a,b,c; // Structure Variable 1
int main() Enter a and b where a + ib is the
{ first complex number.
int choice; a=3
while(1) b=5
{ Enter c and d where c + id is the
printf("Press 1 to add two complex numbers\n"); second complex number.
printf("Press 2 to subtract two complex numbers\n"); c=2
printf("Press 3 to exit\n"); d=6
printf("Enter your choice\n"); Sum of two complex numbers = 5 +
scanf("%d",&choice); 11i
if( choice == 3) Press any key to enter choice
{ again...
exit(0);
} Press 1 to add two complex
if(choice >= 1 && choice <= 2) numbers
{ Press 2 to subtract two complex
printf("Enter a and b where a + ib is the 1st complex number."); numbers
printf("\na = "); Press 3 to exit
scanf("%d", &a.real); Enter your choice
printf("b = "); 2
scanf("%d", &a.img); Enter a and b where a + ib is the
printf("Enter c and d where c + id is the 2nd complex number."); first complex number.

24
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4

printf("\nc = "); a=1


scanf("%d", &b.real); b=1
printf("d = "); Enter c and d where c + id is the
scanf("%d", &b.img); second complex number.
} c=2
if ( choice == 1 ) d=1
{ Difference of two complex
c.real = a.real + b.real; numbers = -1 + 0i
c.img = a.img + b.img; Press any key to enter choice
again...
if ( c.img >= 0 ) Press 1 to add two complex
printf("Sum of two complex numbers = %d + %di", c.real, c.img); numbers
else Press 2 to subtract two complex
printf("Sum of two complex numbers = %d %di",c.real,c.img); numbers
} Press 3 to exit
else if ( choice == 2 ) Enter your choice
{ 3
c.real = a.real - b.real;
c.img = a.img - b.img;

if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}

25

You might also like