0% found this document useful (0 votes)
78 views32 pages

Cs1100lec21 23

This document provides an overview of structures in C programming. It defines structures as collections of variables of different types grouped under a single name. Examples are provided to demonstrate declaring and defining structure variables as well as accessing structure members. Functions can accept structures as arguments and return structures. Arrays of structures are also discussed. Operations on structures like copying and comparing are mentioned. Pointers to structures and self-referential structures are introduced as ways to implement dynamic data structures like linked lists.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views32 pages

Cs1100lec21 23

This document provides an overview of structures in C programming. It defines structures as collections of variables of different types grouped under a single name. Examples are provided to demonstrate declaring and defining structure variables as well as accessing structure members. Functions can accept structures as arguments and return structures. Arrays of structures are also discussed. Operations on structures like copying and comparing are mentioned. Pointers to structures and self-referential structures are introduced as ways to implement dynamic data structures like linked lists.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

CS1100 Computational Engineering

Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

Structures

Collection of one or more variables, possibly of different types, grouped together under a single name for easy handling. For example- a structure which represents a point in a two dimensional plane A mechanism for struct point{ defining compound data types int x; int y; By itself it reserves no storage };
PSK, NSN, DK, TAG CS&E, IIT M 2

Point in 2D 2 integers

Different ways of declaring structure variables struct point{ int x; int y; } point1, point2; struct point point1, point2; struct point point1 = { 3 , 2 };
PSK, NSN, DK, TAG CS&E, IIT M

Storage is allocated now.

You can also initialize on declaration.


3

Accessing the individual values

x and y are called members Referring to members : point1.x , point2.y etc.. printf( Point1: (%d,%d)\n, point1.x, point1.y); point1.x = 0; point1.y = -10;

Cannot access point.x and point.y though

Use instances of structures and not structure names to access members point1.x and point2.x are different Treated like a bundle
4

Members are allocated storage next to each other

PSK, NSN, DK, TAG CS&E, IIT M

Marks and Names

1.

struct student{ char *name; int mark; }s1, s2;

name could itself be a struct made up of first name middle name last name

1. 2.

struct student s1, s2; struct student s1 = { Ramesh , 79 };

PSK, NSN, DK, TAG CS&E, IIT M

A rectangle

struct rectangle{ struct point pt1; struct point pt2; }rect1; Accessing points in the rectangle X is a member of pt1 which is rect1.pt1.x = 4; a member of rectangle. rect1.pt1.y = 5; Or rect1.pt1 = { 4, 5 };
PSK, NSN, DK, TAG CS&E, IIT M 6

Defining new types typedef is used for creating new data types, for example

typedef int Age; Age myAge = 99; typedef and Structures especially a good combination
typedef struct point pointType; pointType point1, point2; This is equivalent to struct point point1, point2;
PSK, NSN, DK, TAG CS&E, IIT M 7

Operations on structures

Structures may be copied by assignment statement &structure is the address of the structure Can be passed to functions and can be returned by functions
one can pass an entire structure one can pass components one can pass a pointer to a structure

Structures may not be compared


PSK, NSN, DK, TAG CS&E, IIT M 8

Functions and structures

Structure as function argument

int IsOrigin(pointType pt) { if( pt.x ==0 && pt.y ==0) return 1; else return 0; }

PSK, NSN, DK, TAG CS&E, IIT M

Structures and functions Structure as return type

pointType MakePoint(int x, int y) { pointType temp; temp.x = x; Observe there is no confusion temp.y = y;
between the two occurrences of x and y

return temp; }
PSK, NSN, DK, TAG CS&E, IIT M 10

A screen and its centre point

struct rect screen; struct point middle; struct point MakePoint(int, int); screen.pt1 = MakePoint(0, 0); screen.pt2 = MakePoint(XMAX, YMAX); middle = MakePoint( (screen.pt1.x + screen.pt2.x)/2, (screen.pt1.y + screen.pt2.y)/2 );
PSK, NSN, DK, TAG CS&E, IIT M 11

adding two points

/* AddPoint: add two points */ struct point AddPoint(struct point p1, struct point p2) { p1.x += p2.x; p1.y += p2.y; return p1; }
PSK, NSN, DK, TAG CS&E, IIT M 12

CS1100 Computational Engineering


Lecture 22 Structures continued
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

13

Point inside a rectangle?

/* IsPtInRect: return 1 if point p is in rectangle r, else return 0 */ int IsPtInRect(struct point p, struct rect r) { return ( p.x >= r.pt1.x && p.x < r.pt2.x && p.y >= r.pt1.y && p.y < r.pt2.y ); } assume pt1 is left bottom coordinate and pt2 is right top
PSK, NSN, DK, TAG CS&E, IIT M 14

a canonical rectangle
#define min(a, b) ((a < b) ? a : b) #define max(a, b) ((a > b) ? a : b)
Ternary Operator : (cond) ? trueValue : falseValue

struct rect CanonRect(struct rect r) rectangle */ { struct rect temp;


temp.pt1.x = min(r.pt1.x, r.pt2.x); temp.pt1.y = min(r.pt1.y, r.pt2.y); temp.pt2.x = max(r.pt1.x, r.pt2.x); temp.pt2.y = max(r.pt1.y, r.pt2.y); return temp; }
PSK, NSN, DK, TAG CS&E, IIT M

/* canonicalize coordinates of

15

Arrays of structures
struct point { int x; int y; } pointArray[] = { { 1,2 }, { 2,3 }, { 3,4 } };

struct point{

int x; int y; } pointArray[10];

pointType pointArray[10];
PSK, NSN, DK, TAG CS&E, IIT M 16

Accessing member values Assigning values to structure elements pointArray[0].x = 1; pointArray[0].y = 2; OR pointArray[i].x = 5; pointArray[i].y = 5; Printing elements of Structures printf( (%d, %d ), pointArray[0].x, pointArray[0].y);
PSK, NSN, DK, TAG CS&E, IIT M 17

structure1 = structure2

Structures can be assigned using the assignment operator struct point newPoint; newPoint = MakePoint(4,4);

PSK, NSN, DK, TAG CS&E, IIT M

18

Structures (review) Often needed requirement keeping related data items as one unit for instance Name, Roll No, Gender, Hostel, Room No of a Student
logically belong together - need to be grouped

the items may be of different types


name -- string rollNo integer gender -- single character hostel string roomNo -- integer
PSK, NSN, DK, TAG CS&E, IIT M 19

Example Structure Definition typedef struct student{ char name[30]; Components can be of any type - even struct int rollNo; char gender; char hostel[8]; Observe the semi-colons int roomNo; } StudentType; Creates - a new data type called StudentType a composite type with 5 components Can be used in type declarations of variables StudentType jayanthi, vikas, mahesh;
PSK, NSN, DK, TAG CS&E, IIT M 20

Another Definition

typedef struct book{ char title[20]; char authors[30]; int accNo; char subject[25]; } BookType; BookType cText; BookType shelf[100];
PSK, NSN, DK, TAG CS&E, IIT M

// a C textbook // a shelf holds 100 books


21

CS1100
Lecture 23 Structures: Complex arithmetic
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

22

Using Structures

Let us create a type for complex numbers and a few operations on complex numbers typedef struct { float real; float imag; } Complex; Complex sum(Complex m, Complex n); Complex product(Complex m, Complex n);
PSK, NSN, DK, TAG CS&E, IIT M 23

Using Complex Type

main( ){ Dot Notation: Complex a,b,c,d; Accessing scanf(%f %f, &a.real, &a.imag); components of a structure scanf(%f %f, &b.real, &b.imag); c = sum(a,b); d = product(a,b); printf(Sum of a and b is %f + i%f\n, c.real, c.imag); printf(Product of a and b is %f + i%f\n, d.real, d.imag);
}
PSK, NSN, DK, TAG CS&E, IIT M 24

Sum and Product Complex Sum(Complex m, Complex n){ Complex p; p.real = m.real + n.real; p.imag = m.imag + n.imag; return (p); } Complex Product(Complex m, Complex n){ Complex p; p.real = (m.real * n.real) - (m.imag * n. imag); p.imag = (m.real * n.imag) + (m.imag * n. real); return (p);

}
PSK, NSN, DK, TAG CS&E, IIT M 25

Pointers to structures pointType point1, *ptr;


the brackets are necessary

point1 = MakePoint(3,4); ptr = &point1; printf((%d,%d), (*ptr).x, (*ptr).y); OR printf((%d,%d), ptr->x, ptr->y);

equivalent short form

The operator ->( minus sign followed by greater than symbol) is used to access members of structures when pointers are used.
26

PSK, NSN, DK, TAG CS&E, IIT M

Precedence and association

Both . and -> associate left to right. They are at top of precedence hierarchy. The following forms are equivalent struct rect r, *rp = &r; r.pt1.x rp -> pt1.x (r.pt1).x (rp -> pt1).x
PSK, NSN, DK, TAG CS&E, IIT M 27

Examples
Given the declaration struct { int len; int *str; } *p; ++p-> len increments len not p
implied paranthesis ++(p-> len)

(++p)-> len p++-> len *p->str *p->str++

have same (*p->str)++ *p++-> str

increments p before accessing len increments p afterwards fetches whatever str points to (-> precedes *) increments str after accessing whatever it points to (just like *s++; -> and ++ precedence and associate left to right) incerements whatever str points to increments p after accessing whatever str points to

PSK, NSN, DK, TAG CS&E, IIT M

28

Dynamic data structures

How does one cater to an uncertain and changing amount of memory requirements?
for example if the number of students writing an online surprise exam is unknown

One way is dynamic tables / arrays


declare an array of some size N if it seems to be getting full declare an array of twice the size and copy all elements into it

The other is to ask for memory for a structure one at a time and link them together
PSK, NSN, DK, TAG CS&E, IIT M 29

Self referential structures

The structure contains a pointer to a structure of the same type


this is in addition to the other data it stores let student contain marks and name
name: Ramesh marks: 76 nextStudent:
name: Rakesh marks: 77 nextStudent:

name: Rajesh marks: 74 nextStudent:

A linked list
PSK, NSN, DK, TAG CS&E, IIT M 30

Computer Solutions

Problem Solving
main purpose of using computers

Steps
clear specification, understanding of the problem remove unnecessary details and retain only the required parameters, constraints of the problem
abstraction - better insight, helps in thinking

find the method of solving the problem


algorithm design - efficiency

express the solution in a programming language


PSK, NSN, DK, TAG CS&E, IIT M 37

References

GN87: Peter Grogono and Sharon Nelson, Problem Solving and Computer Programming, Narosa, 1987 D96 : R G Dromey, How to solve it by computer, Prentice-Hall India, 1996

PSK, NSN, DK, TAG CS&E, IIT M

38

You might also like