Sudeshna Sarkar 7th March 2017

Slides:



Advertisements
Similar presentations
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
Advertisements

C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Structures, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
Senem Kumova Metin STRUCTURES continues CHAPTER 9 in A Book in C.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
1. 2 Introduction Structure Definitions and Declarations Initializing Structures Operations on Structures Members Structures as Functions Parameters Array.
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
Numbers in ‘C’ Two general categories: Integers Floats
Lesson #8 Structures Linked Lists Command Line Arguments.
User-Written Functions
Programming and Data Structures
CO1401 Program Design and Implementation
A bit of C programming Lecture 3 Uli Raich.
CS1010 Programming Methodology
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Structures.
Chapter 2 - Introduction to C Programming
Programming Languages and Paradigms
Quiz 11/15/16 – C functions, arrays and strings
Structures and Unions in C
Programming Paradigms
Student Book An Introduction
Chapter 2 - Introduction to C Programming
Arrays in C.
EECE.2160 ECE Application Programming
Buy book Online -
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Structures.
Chapter 2 - Introduction to C Programming
הגדרת משתנים יום שלישי 27 נובמבר 2018
Chapter 2 - Introduction to C Programming
Functions.
EKT150 : Computer Programming
Sudeshna Sarkar 7th March 2017
Classes and Objects.
Structures, Unions, and Typedefs
Chapter 2 - Introduction to C Programming
CS111 Computer Programming
Arrays, Part 1 of 2 Topics Definition of a Data Structure
WEEK-2.
Data Structures and Algorithms Introduction to Pointers
Chapter 2 - Introduction to C Programming
EECE.2160 ECE Application Programming
Arrays.
EECE.2160 ECE Application Programming
Programming Languages and Paradigms
Variables in C Topics Naming Variables Declaring Variables
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Introduction to C Programming
Arrays, Part 1 of 2 Topics Definition of a Data Structure
EECE.2160 ECE Application Programming
Structures, Unions, and Enumerations
Presentation transcript:

Sudeshna Sarkar 7th March 2017 Structures Sudeshna Sarkar 7th March 2017

Structure Combine heterogeneous data to form a named collection

Structures: basics ideas Structure = collection of variables Members of a structure: variables in the collection Structure = super variable, denotes the memory used for all members. Each structure has a name, the name refers to the super variable, i.e. entire collection. Each structure has a type: the type defines what variables there will be in the collection.

Structure types You can define a structure type for each type of entity that you want to represent on the computer. “Programmer defined type” Example: To represent books, you can define a Book structure type. When you define a structure type, you must say what variables each structure of that type will contain. Example: In a structure to represent books, you may wish to have variables to store the name of the book, its price, …

Defining a structure type General form struct structure-type{ member1-type member1-name; member2-type member2-name; … }; // Don’t forget the semicolon! Example struct Book{ char title[50]; double price; }; A structure-type is a user-defined data type, just as int, char, double are primitive data types. Structure-type name and member names can be any identifiers.

Defines a new type E.g., Name of the type struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Name of the type Note: name of type is optional if you are just declaring a single struct

struct Defines a new type E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Members of the struct

Declaring struct variables struct motor p, q, r; Declares and sets aside storage for three variables , p, q, and r, each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; Declares a pointer to an object of type struct motor

Example A structure definition: struct student { char name[30]; int roll_number; int total_marks; char dob[10]; }; Defining structure variables: struct student a1, a2, a3; A new data-type

Structures Compound data: A date is struct ADate { int month; int day; an int month and an int day and an int year struct ADate { int month; int day; int year; }; struct ADate date; date.month = 9; date.day = 1; date.year = 2005;

Structure Representation & Size struct CharCharInt { char c1; char c2; int i; } foo; foo.c1 = ’a’; foo.c2 = ’b’; foo.i = 0xDEADBEEF; sizeof(struct …) = sum of sizeof(field) + alignment padding Processor- and compiler-specific 62 61 EF BE AD DE c1 c2 i padding x86 uses “little-endian” representation

Members struct name { char first[10]; char midinit; char last[20]; } sname, ename; To access the members of a structure, we use the member access operator “.”. strcpy (sname.first, “Aritra”); sname.midinit = ‘K’; strcpy (sname.last, “Saha”) ;

Defining a structure The composition of a structure may be defined as: struct tag { member 1; member 2; : member m; }; } variable_1, variable_2,…, variable_n;

typedef a typedef is a way of renaming a type struct name { char first[10]; char midinit; char last[20]; } ; typedef struct name nameType; nameType name1, name2; typedef struct { char first[10]; char midinit; char last[20]; } NAMETYPE; NAMETYPE sname, ename;

Processing a Structure The members of a structure are processed individually, as separate entities. A structure member can be accessed by writing variable.member Examples: a1.name, a2.name, a1.roll_number, a3.dob

Operations on struct Copy/assign Get address Access members struct motor p, q; p = q; Get address struct motor p; struct motor *s s = &p; Access members p.volts; (*s).amps; s->amps;

Things you can and can't do Use = to assign whole struct variables Have a struct as a function return type You cannot Use == to directly compare struct variables; can compare fields directly Directly scanf or printf structs; can read fields one by one.

Operations on struct (function call) Passing an argument by value is an instance of copying or assignment Passing a return value from a function to the caller is an instance of copying or assignment struct motor f (struct motor g) { struct motor h = g; ...; return h; }

Struct initializers /* typedef structs go on top */ StudentRecord s1 = {"V Singhal", “17CS1002", 167, 8.31}; Using components of struct variables s1.height = 169; s1.cgpa = 8.4; scanf ("%s", s1.rollno) ;

Example: Complex number addition typedef struct { float real; float imaginary; } complex; int main( ) { complex a, b, c; scanf (“%f %f”, &a.real, &a.imaginary); scanf (“%f %f”, &b.real, &b.imaginary); c.real = a.real + b.real; c.imaginary = imaginary + b.imaginary; printf (“\n %f + %f j”, c.real, c.imaginary); }

Example: Complex number #include <stdio.h> typedef struct { float real; float imaginary; } complex; complex read_complex ( ) { complex c; scanf (“%f %f”, &c.real, &c.imaginary); return c; } void print_complex (complex c) { printf (“ %f + i %f ”, c.real, c.imaginary);

Complex number arithmetic complex add_complex (complex c1, complex c2) { complex csum; csum.real = c1.real + c2.real; csum.imaginary = c1.imaginary + c2.imaginary; return csum; } complex sub_complex (complex c1, complex c2) { complex cdiff; cdiff.real = c1.real + c2.real; cdiff.imaginary = c1.imaginary + c2.imaginary; return cdiff;

Complex number arithmetic complex mult_complex (complex c1, complex c2) { complex cprod; cprod.real = cprod.imaginary = return cprod; } int main ( ) { complex c1, c2, c3, c4; read_complex (c1) ; read_complex (c2) ; c3 = add_complex (c1, c2) ; printf (“Sum of”) ; print_complex (c1) ; printf (“and”); print_complex (c2); printf(“is”) ; print_complex (c3);

Arrays of Structures We can declare an array of structures. struct student class[50]; The individual members can be accessed as: class[i].name class[5].roll_number

struct Arrays typedef struct { double x; double y; } point; point pentagon[5]; struct Arrays pentagon : an array of points x y pentagon[1] : a point structure x y x y pentagon[4].x : a double x y x y

Using Arrays of structs StudentRecord class[MAXS]; … for (i=0; i<nstudents; i++) { scanf (“%d%d”, &class[i].midterm, &class[i].final); class[i].grade = (double)(class[i].midterm + class[i].final)/50.0; }

Passing Arrays of structs An array of structs is an array. When any array is an argument (actual parameter), its address is passed, not copied [as for any array] int avg (StudentRec class[MAX]) { ... … } int main ( ) { StudentRec bt01[MAX]; int average; ... average = avg_midpt(bt01) ;

A function using struct array int fail (StudentRecord slist [ ]) { int i, cnt=0; for (i=0; i<CLASS_SIZE; i++) cnt += slist[i].grade == ‘F’; return cnt; }

Arrays within Structures A structure member can be an array: The array element within the structure can be accessed as: a1.marks[2] struct student { char name[30]; int roll_number; int marks[5]; char dob[10]; } a1, a2, a3;

Structure within Structures A structure member can be another structure: struct college_info {     int college_id;     char college_name[50]; }; struct stud_detail {     int class;     char name[20];     float percentage;     struct college_info college; } student_data;

typedef : An example typedef struct{ float real; float imag; } COMPLEX; COMPLEX a,b,c;

Structure Initialization Structure variables may be initialized following similar rules of an array. The values are provided within the second braces separated by commas. An example: COMPLEX a={1.0,2.0}, b={-3.0,4.0}; a.real=1.0; a.imag=2.0; b.real=-3.0; b.imag=4.0;

Parameter Passing in a Function Structure variables could be passed as parameters like any other variable. Only the values will be copied during function invocation. void swap(COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp=a; a=b; b=tmp; }

An example program #include <stdio.h> typedef struct{ float real; float imag; } COMPLEX; void swap(COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp=a; a=b; b=tmp; }

Example program: contd. void print(_COMPLEX a) { printf("(%f , %f) \n",a.real,a.imag); } main() COMPLEX x={4.0,5.0},y={10.0,15.0}; print(x); print(y); swap(x,y);

Returning structures It is also possible to return structure values from a function. The return data type of the function should be as same as the data type of the structure itself. COMPLEX add (COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp.real = a.real+b.real; tmp.imag = a.imag+b.imag; return(tmp); } Direct arithmetic operations are not possible with Structure variables.

Example-1 Define a structure type student to store the name, roll, and total-marks of any student. Write a program to read this information (from keyboard) for one student and print the same on the screen.

Example-1 CODE:

Example-2 Use the same student structure as described in the Example-1. Define a function to check whether two students are same or not. It returns 1, if the student1 and student2 are same It returns 0, if the student1 and student2 are NOT same

Example-3 Write a C program to perform addition and multiplication of any two complex numbers, taken as input from the terminal.

Exercise Problems Define a structure for representing a point in two-dimensional Cartesian co-ordinate system. Write a function to compute the distance between two given points. Write a function to compute the middle point of the line segment joining two given points. Write a function to compute the area of a triangle, given the co-ordinates of its three vertices.

Problem Statement: Example 4 Write a program which reads two timestamps (hour, minute, second separately in 23:59:59 format) and prints the time difference between them.

Exercise 3 Define a structure data type named date containing three integer members: day, month, and year. Write a program to perform the following tasks: To read data into structure members by a function To print the date in the format: July 11, 2013 To validate the date by another function Example Output: Enter the day, month, and year: 10 9 2016 The date is: September 10, 2016 It is a VALID date Enter the day, month, and year: 31 4 2015 The date is: April 31, 2015 It is an INVALID date

Exercise 4 Use the same date structure as defined in Exercise 1 to store date of birth and current date. Calculate the age of the person.