Beruflich Dokumente
Kultur Dokumente
CMPD 244
Programming II
Lab 4: Structure in C++
In this lab session, you will learn on how to create a program that
includes structure. A data structure is a group of data elements
grouped together under one name. These data elements, known as
members, can have different types and different lengths.
Data structures are declared in C++ using the following syntax:
struct structName{
datatype variableInStruct1; //member of this struct
datatype variableInStruct2; //member of this struct
datatype variableInStruct3; //member of this struct
};
};
From the above example;
a) What is the structure type? Answer:
_____car_____________________
b) How many data members of this new structure type? Answer:
_________2_______
Now, lets create an object of this new type of structure.
car Proton;
car Perodua;
2014
Programming II
Universiti Tenaga Nasional (UNITEN)
This new object can be created within main or any other function
(local variable/object) or can be placed outside of any function
(global variable/object). Local variable/object is visible and can be
used within that specific function.
2014
Programming II
Universiti Tenaga Nasional (UNITEN)
#include <iostream>
#include <string>
using namespace std;
struct car{
char model[20];
int year;
};
int main()
{
car Proton;
car Perodua;
strcpy(Proton.model, "Exora"); //assign value to a structure - string
Proton.year=2010; //assign value to a structure - int
cout << "Perodua" << endl;
cout << "Enter a model name: ";
cin.getline(Perodua.model,20);
cout << "Enter the year: ";
cin >> Perodua.year;
cout << "I have a Proton " << Proton.model << " Year "
<< Proton.year <<endl;
cout << "Your car is Perodua " << Perodua.model << " Year "
<< Perodua.year <<endl;
}
2014
Programming II
Universiti Tenaga Nasional (UNITEN)
struct baverages{
char name[10];
int price;
};
int main()
{
baverages coffee;
baverages tea;
strcpy_s(coffee.name, "Nescafe"); //assign value to a structure - string
coffee.price = 20; //assign value to a structure - int
strcpy_s(tea.name, "Boh Teh"); //assign value to a structure - string
tea.price = 10; //assign value to a structure - int
cout << "Enter a coffee or tea name: ";
cin.getline(coffee.name, 10);
cout << "Name: " << coffee.name << "\n PRICE RM: "
<< coffee.price << endl;
}
Based on the structure type created, create two objects; coffee, tea.
The program should be able to get the input from user and print
out the details of the entered coffee and tea.
Dont forget to submit the screen capture of your output to wanie.cfgs@gmail.com with the
subject: CMPD244 Lab3 <YourStudentID><Your Full Name> at the end of this lab session.
Good Luck!
2014