Ch04 Structures.ppt

download Ch04 Structures.ppt

of 12

Transcript of Ch04 Structures.ppt

  • Introduction to Programming

    Engr. Rashid Farid [email protected]

    Chapter 04: StructuresInternational Islamic University H-10, Islamabad, Pakistanhttp://www.iiu.edu.pk

  • StructuresWe have seen variables of simple data types, such as float, char, and int.Variables of such types represent one item of information: a height, an amount, a count, and so on.But just as groceries are organized into bags, employees into departments, and words into sentences, its often convenient to organize simple variables into more complex entities.The C++ construction called the structure is one way to do this.A structure is a collection of simple variab-les (can be of different types). The data items in a structure are called the members of the structure.

  • A Simple StructureLets start off with a structure that contains three variables: two integers and a floating-point number.This structure represents an item in a widget companys parts inventory. The structure is a kind of blueprint specifying what informat-ion is necessary for a single part.The company makes several kinds of widgets, so the widget model number is the first member of the structure.The number of the part itself is the next member, and the final member is the parts cost. The next program defines the structure part, defines a structure variable of that type called part1, assigns values to its members, and then displays these values.

  • Program to use a structure (1/2)// uses parts inventory to demonstrate structures#include using namespace std;struct part{ // declare a structureint modelnumber; // ID number of widgetint partnumber; // ID number of widget partfloat cost; // cost of part};int main(){part part1; // define a structure variable// give values to structure memberspart1.modelnumber = 6244;part1.partnumber = 373;part1.cost = 217.55F;

  • Program to use a structure (2/2)// display structure memberscout
  • Initializing Structure Members (1/2)// uses parts inventory to demonstrate structures#include using namespace std;struct part{ // declare a structureint modelnumber; // ID number of widgetint partnumber; // ID number of widget partfloat cost; // cost of part};int main(){ // initialize variablepart part1 = { 6244, 373, 217.55F };part part2; // define variable// display first variablecout
  • Initializing Structure Members (2/2)part2 = part1; //assign first variable to second// both variable must be of same data type

    //display second variablecout

  • Placing A Persons Information (1/3)#include #include #include using namespace std;struct date{ int month; int day; int year; };struct student{ char name[80]; char mobile[15]; int age; char email[30]; date birthday;};

  • Placing A Persons Information (2/3)int main(){student sd1;cout
  • Placing A Persons Information (3/3)cout