Presentation on Structure. Structure Structure - It is a collection of variables referenced under one name. The keyword struct tells the compiler that.

Slides:



Advertisements
Similar presentations
Structure.
Advertisements

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.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
True or false A variable of type char can hold the value 301. ( F )
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MCA, MSc[IT], MTech[IT],MPhil (Comp.Sci), PGDCA, ADCA, Dc. Sc. & Engg.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Structure A structure is a collection of variables of different data type under one name. It is a derived data type. e.g. struct employee {int empno; char.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Learners Support Publications Classes and Objects.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
CPS120: Introduction to Computer Science Decision Making in Programs.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Chapter 7 A Data Types – Structures Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Pointers *, &, array similarities, functions, sizeof.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Course Title Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 07 classes 1 BY ADEEL ANJUM ( MSc - cs, CCNA, WEB DEVELOPER )
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
Course Title Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 06 FUNCTIONS 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER) 1.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
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++
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7. 12: Structures Starting Out with C++ Early Objects Eighth.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
A Sample Program #include using namespace std; int main(void) { cout
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7: User-Defined Functions II
Basic Elements of C++.
FUNCTIONS IN C++.
Student Book An Introduction
Data Types – Structures
DATA HANDLING.
Basic Elements of C++ Chapter 2.
Data Types – Structures
Classes and Objects.
Arrays Arrays A few types Structures of related data items
Submitted By : Veenu Saini Lecturer (IT)
Presentation transcript:

Presentation on Structure

Structure Structure - It is a collection of variables referenced under one name. The keyword struct tells the compiler that a structure is being defined Syntax : struct name of structure { data members / members of isotopes } Example: struct date { short day; short month ; short year; } ;

The date is a structure tag and it identifies this particular data structure and its type specifie. After the above definition no structure variable has been declared,that is, no memory space has been reserved.only the form of data has been defined. to declare structure variable having data form as defined by date, date joining_date This declares a structure variable joining_date of type date.thus the complete structure definition is as follows. struct date { short day; short month; short year; }; date joinin_date

The structure joining date will be having its element as day, month and year. The C++ compiler automatically allocates sufficient memory to accommodate the entire element variable that makes up a structure variable These two separate structure statements can be joined also struct date { short day; short month; short year; } joining_date ; The above statement defines a structure type called date and declares a structure variable joining_date

Referencing structure element Once a structure variable has been defined, its members can be accessed through the use of (.) dot operator for example the following code assign 1740 to the year element of birth_date structure element declared earlier : birth_date. year = 1740 ; The structure variable name followed by a period (.) and the element name references to that individual structure element. The syntax for accessing a structure element is structure -name. element-name The structure member are treated just like other variable. Therefore, to print the year of birth_date and can be written as cout <<birth_date.yera ; In the same way to read day,month and year of joining_date we can write Cin>>joining_date.day>>joining_date.month >>joining_date.year;

Initializing structure elements The structure element of a structure can be initialized either separately, using separate assignment statement or jointly, using the notations similar to array initialization for instance, Solution: Struct stutype { short roll ;senior_student.rollno =01 ; short class;senior_student.class = 12 ; float marks;senior_studnet.marks =50.00 ; char grade;senior_student.grade= ‘A’ ; } senior_student, junior_student :

Alternatively, the structure senior_student can be initialized by using the notation used for array initialization, Stutype_senior_student = {01, 12, 50.00, ‘A’} ; The second method of structure initialization defined above, can be used only when the structure variable is defined. It cannot be used before the structure variables have been defined. In the above given statement stutype is the type specifier for senior_student and the structure senior_student is being declared and initialized simultaneously

Structure Assignments Object of structure types can be assigned, passed as function arguments and returned as the result from a function. As can be seen in the following statement one structure variable can be assigned to another : Junior_student = senior_student ; With this statement, the value of each member of senior_student is assigned to the corresponding member of junior_student. One structure variable can be assigned to another only when they are of the same structure type. If you try to assign a variable of one structure type to variable of another type, the complier will report an error. For instance, the following assignment is wrong. Junior _student = date ;

Two structure types are different even when they have the same type of members. For example: Struct one{ int a ; } ; Struct two { int a ; } ; one S1 ; two S2 ; cin >> S1. a ;//read S1 s2 =S1 ;//error : type mismatch The above code fragment will produce an error because S1 and S2, through have similar elements but are of different types one and two respectively, and hence, they cannot be assigned to one another. Only assignment (=) is possible for two similar structures. Other operations, such as comparisons (===and!=) are not defined for similar structures. A structure may be local (to a function), if defined within a function. That is no function other than the one which defines it can access it (the structure). A structure may be global (to all functions within a program) if defined outside all functions. That is any function can then access it.

Nested Structure A Structure element may be either complex or simple. The simple elements are any of the fundamental date types of C++ i.e int char, float, double. However, a structure may consist of an element tht itself is complex i.e, it is made up of fundamental types, e.g., arrays structures etc. A structure consisting of such complex element is called a complex structure. A structure can be nested inside another structure. Following code fragment illustrates it: Struct addr// styructure tag { int houseno ; char area [26] ; char city [26] ; char state [26] ; } ;

Struct emp//structure tag { int empno ; char name [26] ; char design [16] ; addr address ; float basic ; } ; Emp workwer ;// create structure variable The structure emp has been defined having several element including a structure address also. The element address (of structure emp) is structure of type addr. While defining such structures, just make sure that inner structures are defined before outer structures.

Accessing Nested Structure Members The members of structures are accessed using dot operator. To access the city member of address structure which is an element of another structure worker, we shall write Worker. Address. City To initialize houseno member of address structure, element of worker structure, we can write as follow: Worker. Address. Houseno =1694 As you can see, the elements of each structure are referenced from outermost to innermost. Following example program reads values into such a nested structure:

PROGRAM 13.1 Program to read values into a nested structure. #include #include #include Struct addr { int houseno ; Char area [26] ; Char city [26] ; Char state [26] ; } ; Struct emp { int empo ; Char name [26] ; Char design [16] ; addr address ; float basic ; } worker ; int main ( ) { Clrscr ( ) ; Cout > worker. empno : Cout > ‘ can ‘t read them cout << “\n “ << “ Designation :” ; gets ( worker. design) ;

cout > worker. address. houseno ; cout. Worker. basic ; return 0 ; } // end of main ( ) O/P Enter Employee no : 103 Name :Neel Designation : Manager Enter address : House no :321 Area : Sadiq. Nagar City :Delhi State : Delhi Basic Pay : 9800

STRUCTURES AND ARRAYS While arrays are collections of analogous elements, structures assemble dissimilar elements under one roof. Thus both the array and the structure allow several values to be treated together as a single data object. The arrays and structures can b e combined together to form complex data objects. There may be structures contained within an array: also there may be an array as an element of a structure. Let us discuss various combinations of arrays and structures.

Arrays of Structures Array can contain similar elements; the combination having structures within an array is an array of structures. To declare an array of structures, first define a structure and then declare an array variable of that type. PROGRAM 2 Program to store information of 10 employees and to display information of an employee depending upon the employee no given. #include #include // for clrscr ( ) #include // for gets ( ) Struct addr // global definition { int houseno ; char area [26] ; char city [26] ; char starte [26] ; } ; Struct emp { int empo ; Char name [26] ; Addr address ; // another structure

Float basic ; } worker ; emp sales_emp[10] ; void display (int a) ; // creates array of structures of emp type void enter (void ) ; // prototypes declared int main ( ) { Clrscr ( ) ; int eno, I ; char ch ; enter ( ) ; // to read in information into the array do { Cout > eno ; //Ioop to find the given employee no int flag = 0 ; for ( I = 0 ; I < 10 ; ++i) { if ( sales_emp [i ]. Empno == eno) // if found then { display (i) ; flag = 1 ; break ; } }

if ( !flag) { cout > ch ; } while ( ch == ‘y’ ) ; return 0 ; } Void enter (void) { for (int I = 0 ; I > sales_emp[ i ]. Empno ; Cout << “\n “ << “Employee Name : “ ; gets ( sales_emp [ I ]. name ) ;

cout. Sales_emp [ i ]. address. houseno ; cout > sales_emp [ i ]. Basic ; cout << “\n” ; } return ;

} //end of enter ( ) Void display (int a) { cout << “Employee Data” <, “\n” ; Cout << “\n” << Employee no :” << sales_emp [ a ]. Empno ; Cout << “\n” << “Name :” ; Cout. Write ( sales_emp [ a ]. Name, 26) ; Cout << “\n” << “ Designation :” ; Cout. Write( sales_emp [ a ]. Design, 16) ; Cout << “\n” << “ Address :” << sales_emp [a ]. Address. houseno ; Cout. Write ( sales_emp [ a ]. address. area, 26) ; Cout. write ( sales_emp[ a ]. address. city, 26 ) ; Cout. write ( sales_emp [a ]. address. state, 26) ; Cout << “\n” << “Basic pay :” << sales_emp [ a ]. basic ; Cout << “\n” ; return ; }

O/P Employee No : 213 Employee Name : Mehnaaz k. Designation : MD Address : House no : 444 Area : kaka Nagar City : Delhi State : Delhi Basic Pay : Employee No : 336 Employee Name : Raunaa Raj singh Designation : Manager Address : House no : 233 Area : L. K. Puram City : Delhi State : Delhi Basic Pay : 15500

Enter employee no. whose information is to be displayed : 213 Employee Data Employee no: 213 Name : Mehnaaz k. Designation : MD Address : 444 kak Nagar Delhi Delhi Basic Pay : Display more ? (y/n) N

Arrays within Structures A structure element may be either simple or complex. A complex structure may itself be a structure or an array. When a structure element happens to be an array, it is treated in the same way as arrays are treated. The only additional thing is that to access it, its structure name followed by dot (.) and the array name is too given. For example, consider this structure: Struct student { int rollno ; char name [ 21] ; float marks [ 5 ] ; } ; Student learner ; Structure variable learner is of structure type student that contains an element which is an array of 5 floats to store marks of a student in 5 different subjects. Marks of 3 rd subject of structure learner, we shall write

Struct type { int x [ 5 ] [ 5 ] ; Float y ; } svar ; To reference integer 2,4 in x of structure svar, we shall write PROGRAME 3 Program to accept and print a student’s result using a structure having array inside it. #include # include Struct student { int rollno ; char name [ 21 ] ; float marks [ 5 ] ;

char grade ; } ; Student learner ; Void main ( ) // structure variable declared { // read in student data Cout > learner. Rollno ; Cout > learner. marks [ i ] ; } // Determine grade Float avg, total ; Totlal = ( learner. marks [ 0 ] + learner. marks [2] +learner. marks [2] + learner. marks [3] + learner. marks [4] ) ;

Avg = total / 5 ; If ( avg<50) learner. grade = ‘F’ ; else if ( avg<60) learner. grade = ‘c’ ; else if ( avg<80) learner. grade = ‘B’ ; else learnerd. Grade= ‘A’ ; //Print result Cout << “\n” << “\n” <, “student Result :” << “\n ; Cout << “ Roll no :” << learner. rollno << “\t” ; Cout << “Name:” ; Cout. Write (learner. name, 21); Cout << “\n” << “Total Marks:” <, total; Cout << “\t” << “Grade:” <<learner.grade<<endl ; } //end of main ( )

O/P Enter Roll no: 21 Enter Name: Navya Enter marks in 5 subjects: Subject 1: 98 Subject 2: 89 Subject 3: 99 Subject 4: 82 Subject 5: 79 Student result: Roll no:21 Name : Navya Total marks : 457 Grade :A

Passing structure to Function

Call -by -value : when a structure is used as an argument to a function,the entire structure is passed using the standard call - by- value method. This means any changes that any changes made to the contents of the structure inside the function to which it is passed do not affect the structure used as an argument. Program 4 Program to illustrate passing of structure by value. #include #include Struct distance { int feet ; int inches; };

Void main( ) { clrscr ( ); distance length1, length2 ; void prnsum(distance l1,distance l2) ; cout >length.feet ; cout >length1. Inches ; cout >length2.feet ; cout<<”\n” << “inches :” ; prnsum (lngth1, length2) ; return 0; }

void prnsum (distance l1,distance l2) { distance l3 ; l3.feet = l1.feet+ l2.feet+(l1.inches +l2.inches)/12; l3.feet =(l1.inches +l2.inches) % 12; cout<<”\n \n Total feet :” <<l3. feet <<”\n’’; cout<<”totalinches :” <<l3.inches ; getch( ); } O/P Enter length 1: Feet: 6 Enter length 2: Feet: 4 Inches: 5 Total Feet: 10 Total inches: 9

Call- by- reference : when a structure is passed by reference the called function declares a reference for the passed structure and refers to the original structure elements through its reference. Thus the called function works with original values. For e.g. Program 5 #Include #include Struct distance { int feet ; Int inches ; } ; void main ( ) { classcr ( ) ;

Distance lengthl, length2 ; Void prnsum (distance & l1, distance &l2 ) cout > length 1. feet ; cout >length1.inches ; cout >length2.feet ; cout >length2.inches ; prnsum (length1,length2) getch( ); } Void prnsum (distance&.l1,distance& l2) { distance l3 ; l3.feet = l1.feet+ l2.feet+(l1.inches +l2.inches)/12; l3.feet =(l1.inches +l2.inches) % 12; cout<<”\n \n Total feet :” <<l3. feet <<”\n’’; cout<<”Total inches :” <<l3.inches ; getch( ); }

O/P Enter length1: Feet: 3 Inches: 11 Enter length2: Feet: 4 Inches: 5 Total feet: 8 Total inches: 4 # Defines preprocessor directive Preprocessor is a program that is executed before the source code is compiled. The # defines preprocessor allows us to define symbolic names and constant e.g. # include #define PI void main ( ) { int r = 10 ; float cir ; cir = PI* (r * r) ; cout<<”Area of a circle “ <<cir<<endl ; }

Macros Macros are built on the #define preprocessor. A # define preprocessor would look like : #define PI But macro would be look like this: # define SQUARE(X) X*X The main difference is that the first example is a symbolic constant and the second is an expression as #include #define SQUARE (X) X*X void main ( ) { int value = 3 ; cout<< SOUARE (value) ; } After processing the code will become: void main( ) { int value = 3; Cout<< value *value ; } A macros without arguments is treated like a symbolic constant. A macros with argument has its arguments substituted for replacement text, when the macro is expended. A macro substitutes text only ;it does not check for data type

Program 6 Program to display labels of information stored in a structure. # include # include #include #include # define maxlabel 8 struct person { char title[15] ; char firstname [15]; char lastname[15]; char address1[30]; char address2 [25]; char city [25]; char state[25]; long pin ; } ; Void main( ) { person labels[30] ;

Int lab_per_page; For( int i= 0 ; i >labels[i]. firstname; cout >labels[i].lastname ; cout > labels[i].pin ; }

cout > lab_per_pagr ; if (lab_per_page>maxlabels) lab_per_page = maxlabels ; int p = 1, count = 0; char name[30],ctState[50] ; cout<<”\n\t\tPAGE”<<p<<endl; cout.setf(ios::left) ; for(i= 0 ; i<<30) { strcpy(name, labels[i].firstname) ; strcat (name, ‘’ ‘’ ) ; strcpy(name, labels[i].lastname) ; cout<<labels[i]title <<” “ <<setw(30) <<name <<”\t” ; strcpy (name, labels[i+1].firstname) ; strcat (name, ‘’ ‘’) ; strcat( name, labels[i+1].lastname) ; cout<<labels[i+1].title << ‘’ ‘’ <<name<<endl; cout<< setw(30)<<labels[i].address1<<”\t’’ <<setw(30) <<labels[i+1].address1 <<endl; cout<<setw(30)<<labels[i].address2<<”\t’’ <<sew(30) <<labels[i+1].address2 <<endl;

strcpy( ctstate, labels[[i] city) ; strcat(ctState, ‘’ (‘’) ; strcat(ctState, labels[i].state) ; strcat (ctState, ‘’) ‘’) ; cout<< setw(30) << ctState <<”\t”<< labels[i+1].city <<”(“ labels[i+1 ]. state << “)” <<endl ; cout << setw(30) << labels[i].pin<<’’\t’’ <<labels[i+1].pin<<endl ; cout<< endl ; i += 2; count += 2; if ( count ==8 ) { p++ ; count = 0 ; Cout << “\n\t\tPAGE “ << p<<endl ; } } }

Question :Type A 1.Structure brings together a group of : (i)items of the same data type (ii)related data items (iii)integers with user defined names (iv)variables Ans:Related data item. 2.A structure and a class use similar syntax (a) true or (b) false? Ans:True. 3.How are following related? arrys and structure

Arrys: Arrys is a collection of similar elements memory allocated in continues manner refers under one name i.e syntax data type name of array[size of array] Structure: It is a collection pf group of different elements refer under single name. Syntax struct name of student { Data members /members of isotopes } ; 4.In a structure definition, both the structure tag and structure variable list are optional, true or false? Ans: True 5.A structure type reserve space in the memory, True or false? Ans: True.

6.Write a structure specification that includes for float variable called length, breadth height and volume. Call the structure box? Ans: Struct box { float length ; float breadth; float height; float volume; } 7. initialize the first 3 structure elements of question with values 17.5, 11.3, 14.5 and calculate volume as a product of these. Ans : initialize : float A[3] {17.5, 11.3, 14.5}; float V=1; for ( i=0 ; i<3 ; i++) { V= V*A[i]; } Cout<<”volume”<<V;

8. what is the error in the following structure definition? Ans : struct time { Int hrs, mins; } Time t1 ; 9. what is the error in the following structure definition? Ans : struct { // variable name is not declared. Int hrs, mins ; } t1, t2,t3 ;

10.wriote structure definition for structures containing the following: (i) roll no, name, grade (ii) bookno, bookname, author, price (iii)item no, name, price, monthly sales for last 4 months Ans: (i) struct student { int rollno; char name[20]; char grade; } struct book { int bookno; Char book name[20]; Char author[20]; int price } Struct A { int item no; char name[30]; int price; int monthly sales for last 4 months; }

Presented by: Tanya Aneja class-XI B