presentation on structure n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Presentation on Structure PowerPoint Presentation
Download Presentation
Presentation on Structure

Loading in 2 Seconds...

play fullscreen
1 / 45

Presentation on Structure - PowerPoint PPT Presentation


  • 797 Views
  • Uploaded on

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 {

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Presentation on Structure' - nolen


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
structure
Structure
  • Structure - It is a collection of variables referenced under one name.

The keyword structtells the compilerthat a structure is being defined

Syntax : struct name of structure

{

data members / members of isotopes

}

Example: struct date { short day;

short month ;

short year; } ;

slide3

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

slide4

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
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_dateand 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
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:

Structstutype

{ 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:

slide7

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
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 ;

slide9

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
Nested Structure

A Structure element may be either complex or simple. The simple elements are any of the fundamental date types of C++ i.eint 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:

Structaddr // styructure tag

{ inthouseno ;

char area [26] ;

char city [26] ;

char state [26] ;

} ;

slide11

Structemp //structure tag { intempno ; char name [26] ; char design [16] ;addr address ; float basic ; } ;Empworkwer ; // 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
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:

slide13

PROGRAM 13.1 Program to read values into a nested structure. #include<iostream.h> #include<conio.h> #include<stdio.h> Structaddr {inthouseno ; Char area [26] ; Char city [26] ; Char state [26] ; } ;Structemp {intempo ; Char name [26] ; Char design [16] ;addr address ; float basic ; } worker ;int main ( ) { Clrscr ( ) ;Cout << “\n” << “ Enter Employee no : “ << “\n” ;Cin >> worker. empno : Cout << “\ n “ << “Name : “ ; gets (worker.name) : // to read white spaces also as ‘ >> ‘ can ‘t read themcout << “\n “ << “ Designation :” ; gets ( worker. design) ;

slide14

cout << “\n” << “ Enter address :\n” ;cout << “ House no :” ;cin >> worker. address. houseno ;cout << “\n” << “ Area :” ; gets ( worker. address. area) ;cout << ‘\n” << “ City : “ ; gets (worker. address. city) ;cout <, “\n “ <, “ state : “ ; gets (worker. address. state) ;cout << “\n “ <, “ Basic Pay : “ ;cin >. Worker. basic ; return 0 ; } // end of main ( ) O/PEnter Employee no : 103Name :NeelDesignation : ManagerEnter address : House no :321Area : Sadiq. NagarCity :DelhiState : DelhiBasic Pay : 9800

structures and arrays
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
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<iostream.h>

#include<conio.h> // for clrscr ( )

#include<stdio.h> // for gets ( )

Structaddr // global definition

{

inthouseno ;

char area [26] ;

char city [26] ;

char starte [26] ;

} ;

Structemp

{

intempo ;

Char name [26] ;

Addr address ; // another structure

slide17

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

slide18

if ( !flag) { cout <, “\n” << “ Sorry! No such employee exists.” << “\n” ; }Cout <, “\n” << “ Display more ? (y/n).. “ << “\n ;Cin >> ch ; } while ( ch == ‘y’ ) ; return 0 ; } Void enter (void){ for (int I = 0 ; I < 10 ; i++)Cout << “\n” <, Employee No : “ :Cin >> sales_emp[ i ]. Empno ; Cout << “\n “ << “Employee Name : “ ; gets ( sales_emp [ I ] . name ) ;

slide19

cout << “\n” << “Designation : “ ; gets ( sales_emp [ i ]. design) ;cout << “\n” << “Address : “ ;cout << “ House no : “ ;cin >. Sales_emp [ i ]. address. houseno ;cout << “\nArea : “ ; gets ( sales_emp [ i ]. Address. area) ;cout << “\ncity :” ; gets ( sales_emp[ i ]. Address. city) ;cout << “\n State : “ ; gets (sales_emp [ i ]. Address. state) ;cout < “\n” <, “Basic pay :” ;cin >> sales_emp [ i ]. Basic ;cout << “\n” ; } return ;

slide20

} //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 ;}

slide21

O/PEmployee No : 213Employee Name : Mehnaaz k.Designation : MDAddress : House no : 444Area : kaka NagarCity : DelhiState : Delhi Basic Pay : 29900Employee No : 336Employee Name : Raunaa Raj singhDesignation : ManagerAddress : House no : 233Area : L. K. PuramCity : DelhiState : Delhi Basic Pay : 15500

slide22

Enter employee no. whose information is to be displayed :213Employee DataEmployee no: 213Name : Mehnaaz k.Designation : MDAddress : 444 kak Nagar Delhi DelhiBasic Pay : 29900Display more ? (y/n)N

slide23

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 {introllno ; 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 3rd subject of structure learner, we shall write

slide24

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<ioxtream. h> # include < stdio. H>Struct student { introllno ; char name [ 21 ] ; float marks [ 5 ] ;

slide25

char grade ;} ;Student learner ; Void main ( ) // structure variable declared{ // read in student data Cout <, “\n” <, Enter Roll no : “ ;Cin >> learner. Rollno ;Cout << “\n” << “ Enter Name :” ; gets ( learner. name) ;cout << “\n” << “Enter marks in 5 subjects :” << “\n” ; for(int I = 0 ; I < 5 ; i++) { Cout << “\n” << “subject” << I + 1 << “:” ;Cin >> learner. marks [ i ] ; } // Determine grade Float avg, total ;Totlal = ( learner. marks [ 0 ] + learner. marks [2] +learner. marks [2] + learner. marks [3] + learner. marks [4] ) ;

slide26

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 ( )

slide27

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

slide29

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 <iostream.h>#include<conio.h>Struct distance{ int feet ;int inches;};

slide30

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

slide31

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/PEnter length 1: Feet: 6Enter length 2:Feet: 4Inches: 5 Total Feet: 10Total inches: 9

slide32

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<iostream.h>#include<conio.h>Struct distance{ int feet ;Int inches ;} ;void main ( ){ classcr ( ) ;

slide33

Distance lengthl, length2 ; Void prnsum (distance & l1, distance &l2 )cout << “enter lrnhyh 1 : ” << “\n” ;cin >> length 1. feet ; cout <<”\n”<< “Inches :” ; cin>>length1.inches ;cout<<”\n \n Enter length2 :”<<”\n” ;cout<<”feet:” ; cin>>length2.feet ;cout<<”\n”<<”inches :”;cin>>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( );}

slide34

O/PEnter length1: Feet: 3Inches: 11Enter length2:Feet: 4Inches: 5 Total feet: 8Total inches: 4# Defines preprocessor directivePreprocessor 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<conio.h>#define PI 3.14159void main ( ){ int r = 10 ; float cir ; cir = PI* (r * r) ;cout<<”Area of a circle “ <<cir<<endl ;}

macros
Macros

Macros are built on the #define preprocessor.

A # define preprocessor would look like : #define PI 3.142

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<iostream.h>

#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
slide36

Program 6Program to display labels of information stored in a structure.# include<iostream.h># include<stdio.h>#include<string. h>#include<iomanip.h ># define maxlabel 8struct 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] ;

slide37

Intlab_per_page; For( inti= 0 ; i<30 ;i++) { cout<<”\nEnterinformationfor person’<<i+1<<’’:’’<< endl ;cout<<”title(Mr/Mrs) : ‘’;cin>>labels[i]. firstname;cout<<’’lastname:’’ ;cin>>labels[i].lastname ;cout<<” house no, street:” ;ets(labels[i]. address1) ;cout<<’ area : “ ; gets (labels[i] .adderess2) ;cout<<”city :” ;cout<<”state :” ; gets(labels[i. state) ;cout<< “pins : “ ;cin>> labels[i].pin ;}

slide38

cout<<”enter how many labels you want to display per page” ;cin>> 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;

slide39

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
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
slide41

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: True5. A structure type reserve space in the memory, True or false?Ans: True.

slide42

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;

slide43

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 ;

slide44

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 monthsAns: (i) struct student { introllno; char name[20]; char grade; }struct book{ intbookno; 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; }