0% found this document useful (0 votes)
58 views15 pages

LAB 12 Structures: EKT 120 - Computer Programming Laboratory Module

This document describes a lab on using structures in C programming. It defines structures, shows how to declare and initialize structures and structure variables, access structure members, create arrays of structures, pass structures to functions, and structures within structures. Sample programs are provided to demonstrate defining a book structure, declaring and initializing structure variables, accessing members, passing structures to functions, and comparing structure members. The key aspects covered are: - Defining, declaring and initializing structures - Accessing structure members using the dot operator - Creating arrays of structures and structures within structures - Passing structures to functions by value - Sample programs demonstrating use of structures

Uploaded by

ariff mohd
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)
58 views15 pages

LAB 12 Structures: EKT 120 - Computer Programming Laboratory Module

This document describes a lab on using structures in C programming. It defines structures, shows how to declare and initialize structures and structure variables, access structure members, create arrays of structures, pass structures to functions, and structures within structures. Sample programs are provided to demonstrate defining a book structure, declaring and initializing structure variables, accessing members, passing structures to functions, and comparing structure members. The key aspects covered are: - Defining, declaring and initializing structures - Accessing structure members using the dot operator - Creating arrays of structures and structures within structures - Passing structures to functions by value - Sample programs demonstrating use of structures

Uploaded by

ariff mohd
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/ 15

EKT 120 – Computer Programming Laboratory Module

LAB 12
STRUCTURES

School of Computer and Communication Engineering


Universiti Malaysia Perlis
1
EKT 120 – Computer Programming Laboratory Module

1. OBJECTIVES:

1.1 To be able to define, declare and initialize structures.


1.2 To be able to access members of structures.
1.3 To be able to pass structures to functions.
1.4 To be able to create and use structures, arrays of structures and structures within structures
in programs.

2. INTRODUCTION:

Structures are collections of related data items called components (or members) that are not
necessarily of the same data type. Commonly used to define records to be stored in files.

Usually collections of related data item are characteristics of an object.


Object Characteristics
 Book title, price, number of pages, year published
 Car price, model, colour
 Student name, matric_no, grade

2.1 Definition and Declaration of Structures

Before a structure can be used, we need to define the structure


 Syntax Format:
struct <StructureTypeName>
{
structure member declaration list
};

Example:
struct book
{
char title[20];
float price;
int numpages;
int year;
};

Note: struct is the keyword to define a structure.

There are two ways to declare a structure. For example, given a variable name fiction_book, it can
be declared as:

 struct <structure name> <variable_name>;

struct book fiction_book; or

 It can be written directly after the structures definition


struct book
{
char title[20];
float price;
int numpages;
int year;
} fiction_book;

2
EKT 120 – Computer Programming Laboratory Module

2.2 Arrays of Structures

We can also make structures to be in arrays, it is called arrays of structures. For example,

struct employeeType
{
char firstName[20];
char lastName[20];
int personID;
char deptID[10];
double monthlySalary
double monthlyBonus;
};

struct employeeType employees[50]; //We declare 50 elements of array type structure of


//employeeType

2.3 Accessing Members of Structures

To access members of structures, we use the “.” (dot) operator. Refer to the previous fiction_book
for the following examples.

i. To assign the numpages member of fiction_book with 120,


fiction_book.numpages = 120; or
scanf(“%d”,&fiction_book.numpages);

ii. To assign the price member of fiction_book with RM 1.00


fiction_book.price = 1.00; or
scanf (“%d”,&fiction_book.price);

iii. To print members of the structure


printf(“Number of pages in fiction book is %d”, fiction_book.numpages);
printf(“The price for fiction book is %f”,fiction_book.price);

2.4 Structures Within a Structure

Structures within a structure format can be illustrated by the following example:

struct nameType struct contactType


{ char first[30]; { char phone[12];
char middle[30]; char cellphone[12];
char last[20]; char fax[12];
}; char pager[12];
struct addressType char email[50];
{ char address1[40]; };
char address2[40]; struct employeeType
char city[30]; { nameType name;
char state; char emplID[12];
char zip; addressType address;
}; dateType hiredate;
struct dateType dateType quitdate;
{ char month[2]; contactType contact;
char day[2]; char deptID[10];
char year[4]; double salary;
}; };

The struct employeeType contains structures of nameType, addressType, dateType and also
contactType.

3
EKT 120 – Computer Programming Laboratory Module

To access their members, use:

Declare a variable name newEmployee => struct employeeType newEmployee;

 newEmployee.salary = 45678.00;
 newEmployee.name.first = "Mary";
 newEmployee.name.middle = "Beth";
 newEmployee.name.last = "Simmons";

2.5 Sample Program

The following program shows the use of structures in a program.

#include <stdio.h>

struct book //definition of book structure


{
float price;
int numpages;
int year;
};

int main()
{ struct book my_book = {25.50,690,2005}; //declare and initialize my_book
struct book her_book; //declare her_book
printf("\nEnter her book price : ");
scanf("%f", &her_book.price); //to access price member of her_book
printf("\nEnter number of pages of her book : ");
scanf("%d", &her_book.numpages); //to access numpages member of her_book
printf("\nEnter year published of her book : ");
scanf("%d", &her_book.year); //to access year member of her_book

printf("\nMy book : "); //to access members of my_book


printf("\n%.2f\t%d\t%d\n", my_book.price, my_book.numpages, my_book.year);

printf("\nHer book : ");


printf("\n%.2f\t%d\t%d\n", her_book.price, her_book.numpages, her_book.year);

if (my_book.year > her_book.year)


printf("\nMy book is the latest publication\n");
else
printf("\nHer book is the latest publication\n");
return 0;
}

Sample output of the program.

Enter her book price : 30.00


Enter number of pages of her book : 150
Enter year published of her book : 2008

My book :
25.50 690 2005

Her book :
30.00 150 2008

Her book is the latest publication

4
EKT 120 – Computer Programming Laboratory Module
The following program shows the use of structures with functions. The structures variables are
passed by value.

#include <stdio.h>

struct book
{
float price;
int numpages;
int year;
};

struct book read(); //the return type of the function is a structure; another
//way to return more than one value from a function.

void print(struct book, struct book); //function receives two structures as parameters

void compare(int, int);

int main()
{ struct book my_book = {25.50,690,2005};
struct book she_book;
she_book = read(); //call function read, the return value will be received
//by she_book
print(my_book, she_book);

//pass value of member (year) of my_book and she_book to function compare


compare(my_book.year, she_book.year);
return 0;
}

struct book read()


{
struct book her_book;
printf("\nEnter her book price : ");
scanf("%f", &her_book.price);
printf("\nEnter number of pages of her book : ");
scanf("%d", &her_book.numpages);
printf("\nEnter year published of her book : ");
scanf("%d", &her_book.year);
return(her_book);
}

void print(struct book my_book, struct book her_book)


{
printf("\nMy book : ");
printf("\n%.2f\t%d\t%d\n", my_book.price, my_book.numpages, my_book.year);
printf("\nHer book : ");
printf("\n%.2f\t%d\t%d\n", her_book.price, her_book.numpages, her_book.year);
}

void compare(int my_year, int she_year)


{ if(my_year > she_year)
printf("\nMy book is the latest publication\n");
else
printf("\nHer book is the latest publication\n");
}

Sample output of the program.

Enter her book price : 30.00


Enter number of pages of her book : 150
Enter year published of her book : 2008
5
EKT 120 – Computer Programming Laboratory Module

My book :
25.50 690 2005

Her book :
30.00 150 2008

Her book is the latest publication

3. TASKS:

3.1 a. List two major differences between a variable that is an array and a variable that is of a
structured data type. Which would you use to store the catalog description of a course? To
store the names of students in the course?

b. Define a structure according to the information provided:

Structure name - studentType


Structure members -
 name: type char, has 50 characters
 no_ID: type integer
 test1: type float
 test2: type float
 total: type float

c. Declare the following variables:

i. Jason type of studentType.

ii. new_students is an array of studentType, with 5 elements.

3.2 a. Define a structure type sSquareColumnT to represent a square timber column. Components
should include the type of wood (a string of less than 20 characters), the length and width of the
column in inches, and the maximum compressive strength of the wood in whole pounds per
square inch. Here is a variable sq_col that it should be possible to declare using your data type.

sq_col

acType Douglas fir


dLength 84.0
dWidth 6.5
iMaxCompStrength 445

6
EKT 120 – Computer Programming Laboratory Module
(b) Define a structure type inventory containing character array acPartName[30], integer
iPartNumber, floating point fPrice, integer iStock, and integer iReorder.

(c) Define a struct called address, containing character arrays acStreetAddress[25], acCity[20],
acState[3] and acZipcode[6].

(d) Define a structure type cat_num_t to represent a catalog number consisting of a two- or three-
character category code followed by an integer. Then define a structure type cat_entry_t to
represent a catalog entry. Each entry has a catalog number, a description that is a string of up
to 19 characters, a wholesale price, and a retail price.

(e) Define two output functions for the data types you defined in Question 3.2.d: print_cat_num
and print_cat_entry. Output of a catalog entry should resemble the following example.

Number: EXC-412
Description: 2400 BAUD MODEM
Wholesale price: $79.86
Retail price: $119.99

7
EKT 120 – Computer Programming Laboratory Module

(f) Define an interactive input function for catalog numbers. Name the function fnScanCatNum.
The function should prompt the user as follows.

Enter catalog number:


Enter letters before dash>
Enter digits after dash>

Function fnScanCatNum should take a single structured output argument through which it
stores the catalog number entered. The function should return 1 for successful input, 0 for
input error, and EOF if endfile is encountered before any data is obtained.

3.3 a. Give the output of the following program:

#include<stdio.h>
struct tag{
int i;
char acName[32];
} s1={10, "ABCD"};

int main() {
struct tag s2;

s2.i = 2*s1.i;
strcpy(s2.acName, s1.acName);
strcat(s2.acName, "1234");
printf("s2.i = %d\n", s2.i);
printf("s2.acName= %s\n", s2.acName);
return 0;
}

8
EKT 120 – Computer Programming Laboratory Module
b. Give the output of the following program:

#include <stdio.h>

struct tag {
char *p;
char acName[32];
} s = {"abcd", "ABCD"};

int main() {
printf("s.p = %s\n", s.p);
printf("s.p[1] = %c\n", s.p[1]);
printf("s.acName = %s\n", s.acName);
printf("s.acName[0] = %c\n", s.acName[0]);
printf("s.acName[1] = %c\n", s.acName[1]);
printf("*s.acName = %c\n", *s.acName);
return 0;
}

c. Give the output of the following program:

#include<stdio.h>
struct tag
{
int i;
int j;
} s1;

struct tag funct(int a)


{
static int i =10;
int j = a+i;
i++;
s1.i = i;
s1.j = j;
}

int main()
{
struct tag s;
s = funct(1);
printf("s.i = %d\n", s1.i);
printf("s.j = %d\n", s1.j);
s = funct(2);
printf("s.i = %d\n", s1.i);
printf("s.j = %d\n", s1.j);
return 0;
}

9
EKT 120 – Computer Programming Laboratory Module

d. Give the output of the following program:

#include <stdio.h>

struct data {
int a;
float b[10];
} DATA;

int main() {
DATA d;
struct data *p;

d.a = 10;
d.b[2] = 10;
p = &d;
p->a = d.a;
p->b[1]= 2*d.b[2];
printf("p->a= %d\n", p->a);
printf("p->b[1]= %f\n", p->b[1]);
return 0;
}

3.3 Define a structure type to represent a common fraction. Write a program that gets a fraction and
displays both the fraction and the fraction reduced to lowest terms using the following code
fragment:
frac = get_fraction();
print_fraction(frac);
printf(“=”);
print_fraction(reduce_fraction(frac);

Sample output 1:
Input fraction (num/den) : 8/6
8/6 = 4/3

Sample output 2:
Input fraction (num/den) : 2/6
2/6 = 1/3

10
EKT 120 – Computer Programming Laboratory Module

11
EKT 120 – Computer Programming Laboratory Module

3.4 Numeric addresses for computers on the international network internet are composed of four
parts, separated by periods, of the form

xx.yy.zz.mm

where xx, yy, zz and mm are positive integers. Locally, computers are usually known by a
nickname as well. You are designing a program to process a list of Internet addresses, identifying
all pairs of computer from the same locality. Create a structure type called address_t with
components for the four integers of an internet address and a fifth component in which to store an
associated nickname of 10 characters. Your program should read a list of up to 100 addresses
and nicknames terminated by a sentinel address of all zeros and a sentinel nickname.

Sample data
111.22.3.44 platte
555.66.7.88 wabash
111.22.5.66 green
0.0.0.0 none

The program should display a list of message identifying each pair of computers from the same
locality – that is, each pair of computers with matching values in the first two components of the
address. In the message, the computers should be identified by their nicknames.

Example Message
Machines platte and green are on the same local network.

Follow the message by a display of the full list of addresses and nicknames. Include in your
program a fnScanAddress function, a fnPrintAddress function, and a fnLocalAddress function.
Function fnLocalAddress should take two address structures as input parameters and return 1 (for
true) if the addresses are on the same local network, and 0 (for false) otherwise.

12
EKT 120 – Computer Programming Laboratory Module

13
EKT 120 – Computer Programming Laboratory Module
3.5 Table 12.1 shows a list of best seller books in a book store. Write a program to calculate the total
price for all the books sold. If the quantity sold is greater than or equal to 40 copies, a discount of 10%
will be deducted from the book’s price. Display book’s title, price, quantity, total price, discounted
amount and price after discount for each book, and finally calculate the total of amount payable to the
book’s supplier.

Book’s Title Price (RM) Quantity Sold


C_Programming 79.10 40
Dictionary 49.50 20
EasyAnalog 70.50 30
Electronics 125.60 10
Linux101 59.95 50

Table 12.1

Requirement:
(a) Define and declare struct bookType with title (char), price (float), qty (int) and total
(float) as members.
(b) Declare an array named discount to store calculated discount amount.
(c) Declare an array named after_discount to store calculated total amount after
discount.
(d) Declare an array of structure bookType named book to store all the information for
five (5) books.

Sample Output:

Enter book title : C_Programming

Enter book price : RM 79.10

Enter quantity ordered : 40


…….

Book's Title Price Quantity Total Discount After Discount


C_Programming 79.10 40 3164.00 316.40 2847.60
Dictionary 49.50 20 990.00 0.00 990.00
EasyAnalog 70.50 30 2115.00 0.00 2115.00
Electronics 125.60 10 1256.00 0.00 1256.00
Linux101 59.95 50 2997.50 299.75 2697.75

Total amount payable : RM 9906.35

14
EKT 120 – Computer Programming Laboratory Module

15

You might also like