0% found this document useful (0 votes)
8 views

module 3

Uploaded by

stickman8068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

module 3

Uploaded by

stickman8068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Module 3

CHAPTER 12 Enumerated, Structure


and Union types

1. With proper format and example explain typedef and enumerated type.
Typedef:

A type definition (typedef), gives a name to a data type by creating a new data type
that can then be used anywhere a type is permitted.

Ex: char*stringPtrAry[20];

We can simplify the declaration by using the type definition to create string type and
then defining the array using the new type as below:

typedef char*STRING;

STRING StringPtrArt[20];

The structure defined using the keyword typedef is called type defind structure.

Syntax:

typedef struct

datatype member1;

datatype member2;

---------------
} tagName;

Ex:

typedef struct

char name[20];

float salary;

int empno;

} employee;

Enumerated type:

The enumerated type is a user defined type based on the standard integer type. In an
enumerated type, each integer value is given an identifier called an enumeration
constant.

Declaring and enumerated type:

To declare an enumerated type, we must declare its identifier and its values. Because
it is derived from the integer type, it's operations are the same as for integers.

Syntax:

enum type name{identifier list};

enum-keyword

typeName-name given to enum type

Identifier list (uppercase)-these are the constant values that belong to enum.

Each enumeration identifier is assigned an integer value.

If we do not explicitly assign the values, the compiler assigned the first identifier as
the value 0 and second identifier as 1 and so on and incremented by 1

Ex: enum color{RED,BLUE, GREEN, WHITE};

The color type has four and only four possible values. The range of values is 0---3
with the identifier,

red representing value 0,


blue as 1,

green as 2,

and white as 3.

Once we have declared an enumerated type, we can create variables from it just as
we can create variables from standard types.

C allows the constants, or variables that hold enumerated constants, to be used


anywhere, that integers can be used

Below example defines 3 variables for our color type:

1.enum color productColor;

2. enumcolor skyColour;

3. enum color flagColour;

Q2 Define structure with example .Discuss two ways to declare structure.


Definition of Structure

Structure is a collection of elements of same or different data types under a single


name.

Syntax:

struct tagName

datatype member1;

datatype member2;

------------

------------

datatype membern;

};

Example :

struct employee

{
char name[20];

float salary;

int empno;

};

Declaring Structure Variables:

• A structure variable declaration is similar to the declaration of variables of any


other data types. It includes the following elements:

1. The keyword struct.

2. The structure tag name.

3. List of variable names separated by commas.

4. A terminating semicolon.

Syntax: struct tagName variable1,variable2;

Eg: struct employee emp1,emp2;

• It is also allowed to combine both the structure definition and variables


declaration in one statement.

• The declaration

struct book_bank

char title[20];

char author[15];

int pages;

float price;

} book1, book2, book3;

is valid. The use of tag name is optional here.

Q3. Differentiate between structure and array.Give example.


1.Definition: A structure is a composite data type that groups together variables
under one name.

• An array is a collection of variables of the same type accessed by a common name.

2.Usage: Structures are used to represent complex data types with multiple fields

• while arrays are used to store multiple elements of the same data type.

3.Access: In a structure, each field is accessed using a unique name

• while in an array, elements are accessed using an index number.

4.Size: The size of a structure is determined by the sum of the sizes of its individual
fields

• while the size of an array is determined by the number of elements multiplied by


the size of each element.

5.Memory Allocation: Each instance of a structure can have different sizes

• while all elements of an array are of the same size.

6.Initialization: Structures are initialized by assigning values to their individual fields,

• whereas arrays are initialized by providing a list of values enclosed in curly braces.

7.Flexibility: Structures provide flexibility in terms of the types and numbers of fields
they can have

• while arrays have a fixed size and type for all elements.

8.Manipulation: Structures allow for manipulation of individual fields independently

• while arrays require manipulation of entire elements.


9.Passing to Functions: Structures are usually passed to functions by reference
(address)

• while arrays can be passed either by reference or by value.

10. Syntax

• Structure:

Struct structure_name {

Data_type member1;

Data_type member2;

// and so on…

};

• Array:

Data_type array_name[size];

11.Example:

// Structure Example

Struct Person { char name[50];

Int age;

Float height; };

// Array Example

Int numbers[5] = {1, 2, 3, 4, 5};

Q4. MULTIPLY FRACTIONS USING STRUCTURES


#include<stdio.h>

typedef struct

int numerator;

int denominator;

}Fraction;
int main()

Fraction fr1;

Fraction fr2;

Fraction fr3;

printf(“Key first fraction in the form of x/y:”);

scanf(“%d/%d”,&fr1.numerator,&fr2.numerator);

printf(“Key second fraction in the form of x/y:”);

scanf(“%d/%d”,&fr1.denominator,&fr2.denominator);

res.numerator=fr1.numerator*fr2numerator;

res.denominator=fr1.denominator*fr2denominator;

printf(“\nThe result of %d/%d*%d%d is %d/%d”,


fr1.numerator,fr1.denominator,fr2numerator,fr2.denominator,res.numerator,res.de
nominator);

return 0;

OUTPUT 1:

Key first fraction in the form of x/y: 3/8

Key second fraction in the form of x/y: 4/1

The result of 3/8*4/1 is 12/8

OUTPUT 2:

Key first fraction in the form x/y: 5/9

Key second fraction in the form x/y: 6/7

The result of 5/9*6/7 is 30/63

Q5 With example illustrate three ways to reference the fields of a


structure.
The three ways to reference the fields of a structure are

a. Direct selection (dot operator) :


Dot operator is used to access the members of a structure directly.
Syntax:
structure_name.member_name
PROGRAM:
#include <stdio.h>
struct employee
{
char name[10];
int salary ;
int empno;
};
void main()
{
struct employee e = {"Vignesh",10000,24} ;
printf("Name : %s\n",e.name);
printf("Salary : %d\n",e.salary);
printf("Employee no. : %d",e.empno);
}
Output:
Name : Vignesh
Salary : 10000
Employee no. : 24

b.Indirection(using a pointer):

This involves creating a temporary pointer to the structure and then using
the * operator to access the members of the structure.

Syntax:

(*ptr).member_name

PROGRAM:

#include <stdio.h>

typedef struct

{
char name[10];

int sem;

}student;

void main()

student s = {"Sanketh",2};

student *ptr;

ptr = &s;

printf("Referred by pointer is \n");

printf("Name : %s\n",(*ptr).name);

printf("Sem : %d\n",(*ptr).sem);

Output:

Referred by pointer is

Name : Sanketh

Sem : 2

c.Indirect selection(using arrow operator):

This is used when there is a pointer to a structure. It’s denoted by dash followed by a
greater than sign(->). It dereferences the pointer and then accesses the member of
the structure.

Syntax:

ptr->member_name

PROGRAM:

#include <stdio.h>

typedef struct

{
char name[10];

int sem;

}student;

void main()

student s = {"Tejas",2};

student *ptr;

ptr = &s;

printf("Accessed by arrow operator of a pointer is \n");

printf("Name : %s\n",ptr->name);

printf("Sem : %d\n",ptr->sem);

Output:

Accessed by arrow operator of a pointer is

Name : Tejas

Sem : 2

Q6. How structure can be nested? Give example program to demonstrate


the nested structure.

A nested structure in C is a structure within structure. One structure can be declared


inside another structure in the same way structure members are declared inside a
structure.

Syntax:

struct name_1
{
member 1;
member 2;
.
.
member n;

struct name_2
{
member_1;
member_2; Inner Structure

member n;
} var1

} var2

Example:

struct person

char name;

int age;

float height;

struct date

int day;

int month;

int year;

} d;

} p;

Here, the inner structure date contains a variable named d with three members.
Which are day, month and year,where as the outer structure person contains
variable of name p with members as name, age, height and a structure date.

Declaration and Initialization:

struct person p = {“John”,30,6.0,{20,1,1993}}


OR

p.name =”John”, p.age =30, p.height = 6.0, p.d.day =20, p.d.month=1,


p.d.year=1993

The member of a nested structure can be accessed using the following syntax:

Syntax:

Variable name of Outer_Structure .Variable name of Nested_Structure .data


member to access

Here in the above example,

p.name

p.age Accessesing outer structure members.

p.height

p.d.day

p.d.month Accessesing inner structure members.

p.d.year

Example:

printf(“ Name = %s \n”,p.name);

printf(“ Age = %d \n”,p.age);

printf(“ Birth Date = %d-%d-%d \n”,p.d.day, p.d.month, p.d.year);

OUTPUT

Name = John

Age = 30

Birth Date = 20-1-1993

Q7 Differentiate between structure and union. Give example.


Parameter Structure Union

Keyword A user can deploy the A user can deploy the keyword union to
keyword struct to define a define a Union.
Structure.

Internal The implementation of In the case of a Union, the memory allocation


Implementation Structure in C occurs internally- occurs for only one member with the largest
because it contains separate size among all the input variables. It shares
memory locations allotted to the same location among all these
every input member. members/objects.

Accessing A user can access individual A user can access only one member at a given
Members members at a given time. time.

Syntax The Syntax of declaring a The Syntax of declaring a Union in C is:


Structure in C is: union [union name]

struct [structure name] {

{ type element_1;

type element_1; type element_2;

type element_2; .

. .

. } variable_1, variable_2, …;

} variable_1, variable_2, …;
Size A Structure does not have a A Union does not have a separate location for
shared location for all of its every member in it. It makes its size equal to
members. It makes the size of a the size of the largest member among all the
Structure to be greater than or data members.
equal to the sum of the size of
its data members.
Value Altering Altering the values of a single When you alter the values of a single
member does not affect the member, it affects the values of other
other members of a Structure. members.
Storage of Value In the case of a Structure, there In the case of a Union, there is an allocation
is a specific memory location of only one shared memory for all the input
for every input data member. data members. Thus, it stores one value at a
Thus, it can store multiple time for all of its members.
values of the various members.
Initialization In the case of a Structure, a In the case of a Union, a user can only initiate
user can initialize multiple the first member at a time.
members at the same time.

8. Write a C program to pass structures through pointers.


->Here's an example C program that calculates the area and perimeter of a rectangle
using structures passed by pointers:

#include <stdio.h>

// Define a structure for rectangle

struct Rectangle {

float length;

float width;

};

// Function to calculate area and perimeter using pointers

void calculate(struct Rectangle *rect, float *area, float *perimeter) {

*area = rect->length * rect->width;

*perimeter = 2 * (rect->length + rect->width);

int main() {

// Declare a structure variable

struct Rectangle r;

float area, perimeter;

// Input length and width of the rectangle

printf("Enter length of rectangle: ");

scanf("%f", &r.length);

printf("Enter width of rectangle: ");

scanf("%f", &r.width);

// Call the function to calculate area and perimeter using pointers

calculate(&r, &area, &perimeter);


// Print the results

printf("Area of rectangle: %.2f\n", area);

printf("Perimeter of rectangle: %.2f\n", perimeter);

return 0;

Output 1:

Enter length of rectangle: 5

Enter width of rectangle: 3

Area of rectangle: 15.00

Perimeter of rectangle: 16.00

Output 2:

Enter length of rectangle: 7.5

Enter width of rectangle: 4.2

Area of rectangle: 31.50

Perimeter of rectangle: 23.40

9.Write a C program to demonstrate passing and returning structure.


#include <stdio.h>

typedef struct

int numerator;

int denominator;

}Fraction;
Fraction getFr(void);

Fraction multFr (Fraction fr1,Fraction fr2);

void printFr(Fraction fr1,Fraction fr2,Fraction result);

int main(void)

Fraction fr1;

Fraction fr2;

Fraction res;

fr1 = getFr();

fr2 = getFr();

res = multFr (fr1,fr2);

printFr(fr1,fr2,res);

return 0;

Fraction getFr(void)

Fraction fr;

printf("Write a fraction in the form of x/y:");

scanf("%d/%d",&fr.numerator,&fr.denominator);

return fr;

Fraction multFr(Fraction fr1,Fraction fr2)

Fraction res;

res.numerator=fr1.numerator*fr2.numerator;
res.denominator=fr1.denominator*fr2.denominator;

return res;

void printFr (Fraction fr1,Fraction fr2,Fraction res)

printf("\n The result of %d/%d * %d/%d is


%d/%d\n",fr1.numerator,fr1.denominator,fr2.numerator,fr2.denominator,res.numer
ator,res.denominator);

return;

Output 1

Write a fraction in the form of x/y:2/5

Write a fraction in the form of x/y:3/4

The result of 2/5 * 3/4 is 6/20

Output 2

Write a fraction in the form of x/y:20/3

Write a fraction in the form of x/y:10/6

The result of 20/3 * 10/46 is 200/18

Program explanation:

In this program a typedef structure having the member numerator,denominator and


having a variable named Fraction are declared. Here f1,f2,res are the values to be
given to the variable Fraction.The program uses three fuctions to get input(getFr),to
multiply the numerator and denominator of two numbers(multFr) and to print the
result(printFr).As the program is done using a structure the values are accessed using
a dot operator i,e f1.numerator.

Q10 With C program demonstrate how function can access the members
of a structure in three ways.
#include <stdio.h>

typedef struct

char name[100];

int jersey;

}PLAYER;

void main()

PLAYER p1 = {"MS DHONI",7};

PLAYER p2 = {"VIRAT KOHLI",18};

PLAYER *ptr;

ptr = &p2;

printf("Accessing directly by direct selection: %s\t%d\n",p1.name,p1.jersey);

printf("Accessing indirectly by indirection: %s\t%d\n",(*ptr).name,(*ptr).jersey);

printf("Accessing indirectly by indirection selection: %s\t%d",ptr->name,ptr-


>jersey);

OUTPUT:

Accessing directly by direct selection: MS DHONI 7

Accessing indirectly by indirection: VIRAT KOHLI 18

Accessing indirectly by indirection selection: VIRAT KOHLI 18

THERE IS NO Q11
Q12 With an example illustrate operations on structure.
The structure is an entity that can be treated as a whole.However, only one
operation,assignment is allowed on the structure itself.That is, a structure can only
be copied to another structure of the same type using the assignment operator.

Rather than assign individual members when we want to copy one structure to
another,as we did earlier,we can simply assign one to the other.

Eg:

In the above example structure values of sam1 is assigned to structure sam2.Before


the data members of sam2 were x=7,y=3,t=0.0 and R=u where as after assigning
sam1 to sam2 data members of sam2 became equivalent to sam1. Therefore after
assignment both structure members are of same values.

Q13 Write a c program to demonstrate union datatype

Ans The union is a construct that allows memory to be shared by different type of
data. This redefinition can be a simple as redeclaring an integer as four characters or
as complex as redeclaring an entire structure.
The union follows the same format syntax as the structure .In fact with the exception
of the keyboards struct and union the formats are the same
SYNTAX
Union shareData
{
Char chAry[2];
Short num;
};

Ex : to demonstrate union for short int , two char

#include < stdio.h>


typedef union
{
Short num;
Char chary[2];
} SH_CH2;
int main()
{
SH_CH2 data;
data.num = 16706;
Printf(“short: %hd\n”, data.num);
Printf(“Ch[0]: %c\n”, data.chAry[0]);
Printf(“Ch[1]: %c\n”, data.chAry[1]);
Return 0;
}
Out put short: 16706
Ch[0]: A
Ch[1]: B
To demonstrate how to use union
#include <stdio.h>
Union un
{
Int member1;
Char member2;
Float member3;
};
int main()
Union un var1;
var1.member1=15;
Var.1member = 15;
Printf(“the value stored in member1 = %d”,var1.member1);
Return 0;
}

Out put
The value stored in member1=15

Q14. Write a C program that uses a function that accepts the structure
representing a point (a point in a plane can be represented by its two
coordinates, x and y) and returns an integer 1, 2, 3, or 4 that indicates in
which quadrant the point is located.
Logic: The program defines a structure Point to represent a point in a plane with two
integer coordinates x and y. The function getQuadrant takes a Point structure as
input and returns an integer representing the quadrant in which the point is located.
It uses conditional statements to determine the quadrant based on the signs of the
coordinates. If x-coordinate and y-coordinate values of the Point are positive, then
the point is in first quadrant. If x-coordinate value is negative and y-coordinate value
is positive, then the point is in second quadrant. If x-coordinate and y-coordinate
values of the Point are negative, then the point is in third quadrant. If x-coordinate
value is positive and y-coordinate value is negative, then the point is in fourth
quadrant.

In the main function, the user inputs the coordinates of the point. The program then
calls the getQuadrant function to determine the quadrant of the point and outputs
the result accordingly.

C Program

#include <stdio.h>

struct Point

int x; int y;

};

int getQuadrant(struct Point p)

{
if (p.x > 0 && p.y > 0) {

return 1; // First quadrant

else if (p.x < 0 && p.y > 0) {

return 2; // Second quadrant

else if (p.x < 0 && p.y < 0) {

return 3; // Third quadrant }

else if (p.x > 0 && p.y < 0) {

return 4; // Fourth quadrant }

else

return 0; // On axis or origin

} int main()

struct Point p;

printf("Enter the x-coordinate of the point: ");

scanf("%d", &p.x);

printf("Enter the y-coordinate of the point: ");

scanf("%d", &p.y);

int quadrant = getQuadrant(p);

switch (quadrant)

case 1: printf("The point is in the first quadrant.\n");


break;

case 2: printf("The point is in the second quadrant.\n");

break;

case 3: printf("The point is in the third quadrant.\n");

break;

case 4: printf("The point is in the fourth quadrant.\n");

break;

default: printf("The point is on an axis or at the origin.\n");

break;

return 0;

Output: 1. Enter the x-coordinate of the point: 5

Enter the y-coordinate of the point: -6

The point is in the fourth quadrant.

2. Enter the x-coordinate of the point: 6

Enter the y-coordinate of the point: -3

The point is in the third quadrant.

You might also like