[go: up one dir, main page]

0% found this document useful (0 votes)
3 views67 pages

Chapter-2 (2)

Chapter 2 covers arrays and structures in programming, explaining the differences between homogeneous and heterogeneous data types. It details how to declare, access, and manipulate arrays, including one-dimensional and two-dimensional arrays, as well as string manipulation using arrays. The chapter also discusses user-defined data types and provides examples of array initialization and usage.

Uploaded by

tsdtech777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views67 pages

Chapter-2 (2)

Chapter 2 covers arrays and structures in programming, explaining the differences between homogeneous and heterogeneous data types. It details how to declare, access, and manipulate arrays, including one-dimensional and two-dimensional arrays, as well as string manipulation using arrays. The chapter also discusses user-defined data types and provides examples of array initialization and usage.

Uploaded by

tsdtech777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Chapter -2

Arrays and Structure

2
Outlines
 Homogeneous and heterogeneous data types

 Difference b/n Arrays and Structure data types

 Declaring, accessing and processing arrays

 String manipulation using arrays

 Multidimensional arrays

 User defined data types (UDT)

3
Homogeneous and Heterogeneous Data Types
o Homogeneous Data structures: All the elements in the structure are the
same data type. Homogeneous means the same type.
o Arrays are homogeneous, since you declare the single type as part of the definition
o The data structures which will accept same type of data type is called a
homogeneous data structure.
o Examples are arrays, strings etc.

o Heterogeneous Data structure: The elements in the structure are of different


data types.
o Heterogeneous means diverse types. example: a record or a struct in c++
o The data structure which will accept different type of data types is called a
heterogenous data structures. Examples are structures, union.
4
Difference Between Arrays and Structure Data Types
o The primary difference between Structures and Arrays is that Arrays can only hold
elements of the same data type, while Structures can hold elements of different data
types.
o Arrays also require a defined size at the point of declaration, which is specified within
square brackets following the Array name.
o An array consists of elements of the same (homogeneous) data types. In contrast, a
structure is a collection of elements of different (heterogeneous) data types.
o A structure may contain elements of different data types : int, char, float, double, etc.
o It may also contain an array as its member. Such an array is called an array within a
structure.
o An array within a structure is a member of the structure and can be accessed just as we
access other elements of the structure
o An array of structures finds its applications in grouping the records together and
provides for fast access.
Cont’d

Arrays and Structures are two different types of container datatype. The most basic difference
between an array and a structure is that an Array can contain the elements of same datatype,
while a Structure is a collection that can contain the elements of dissimilar datatypes.
Array
7
Introduction
 An array is a collection of variables of the same type that are

referred to by a common name.

 An array is a consecutive group of memory locations that all have

the same name and the same type.

 For referring to a particular location, we specify the name and

then the positive index into the array. The index is specified by
square brackets, [].

 Arrays offer a convenient means of grouping together several

related variables, in one dimension or more dimensions:


 What is the concept dimension in array?
8
Dimension in Arrays
 Declaring the name and type of an array and setting the number

of elements in an array is called dimensioning the array.


 The array must be declared before one uses in like other

variables.
 In the array declaration one must define:

1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the
maximum value of each subscript. i.e. the number of elements in
the array.
9
Cont…
 So the general syntax for the declaration is:
DataType name arrayname [array size];
int Student_list[50];
 The expression array size, which is the number of
elements, must be a constant such as 10 or a symbolic
constant declared before the array declaration, for
which the values are known at the time compilation
takes place.
const int N = 50;
float Student_result[N];

10
Product part numbers:
Cont...
int part_numbers[] = {1, 3, 8, 9};

Student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 5, 6}

Characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};

Names:

char names[][40] = {“Mikyas”, “Melat”, “Lilita”, “Jemal”, “ Solomon”};

2D coordinates: vector coordinates[4][3] ={{0, 0, 0},

{1, 0, 1},

{1, 0, 5},

11 {4, 7, 9}};
Initializing Arrays
When declaring an array of local scope (within a
function), if we do not specify the array variable will
not be initialized, so its content is undetermined until
we store some values in it.
If we declare a global array (outside any function) its
content will be initialized with all its elements filled
with zeros.
Thus, if in the global scope we declare: int day [5];
every element of day will be set initially to 0:
0 1 2 3 4
day
12
Cont…
 But additionally, when we declare an Array, we have the
possibility to assign initial values to each one of its elements
using twisted brackets { } .
For example:
int day [5] = { 16, 2, 77, 40, 12071 };
 The above declaration would have created an array like the
following one:
0 1 2 3 4
day 16 2 77 40 12071

13
Cont…
 C++ allows the possibility of leaving empty the brackets [ ],

where the number of items in the initialization bracket will be


counted to set the size of the array.

int day [] = { 1, 2, 7, 4, 12,9 };

• The compiler will count the number of initialization items

which is 6 and set the size of the array day to 6 (i.e.: day[6])

14
Cont…
 You can use the initialization form only when defining the array.

 You cannot use it later, and cannot assign one array to another once. I.e.

int arr [] = {16, 2, 77, 40, 12071};


int ar [4];
ar[]={1,2,3,4, 5};//not allowed
arr=ar;//not allowed
Note: when initializing an array, we can provide fewer values than the
array elements. E.g. int a [10] = {10, 2, 3}; in this case the compiler
sets the remaining elements to zero.

15
Accessing and processing array elements
 To access individual elements, index or subscript is used.

 The format is the following: name [ index ] .

 In C++ the first element has an index of 0 and the last

element has an index, which is one less the size of the array
(i.e. arraysize-1).

 Thus, from the above declaration, day[0] is the first element

and day[4] is the last element.

16
Cont…
The previous examples where day had 5 elements and each
element is of type int, the name, which we can use to refer to
each element, is the following one:
day(0) day(1) day(2) day(3) day(4)
day 16 22 77 40 12071

 For example, to store the value 77 in the third element of the


array variable day a suitable sentence would be:
day[2] = 77; //as the third element is found at index 2
 And, for example, to pass the value of the third element of the
array variable day to the variable a , we could write:
 a = day[2];

17
1. #include<iostream> Cont…
2. int main() {

3. int numbers[5] ={10,20,30,40,50}; //array declaration &


initialization

4. int sum, average; //declaring variables that store sum


and average of array elements

5. sum = 0,average=0; //initializing sum & average to 0

6. cout<<numbers[3]<<endl;

7. for (int i = 0; i <5; i++) {

8. sum += numbers[i];
11. cout<<"The Sum of Array Elements="<<sum<<endl;
9. average = sum / 5;
12. cout<<"The Average of Array Elements="<<average;
10. } //end of for loop
13. return 0;

14. }
18
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general
form of a one-dimensional array declaration is:
type variable_ name[size]
 type: base type of the array, determines the data type of each element in the

array

 variable_name: the name of the array

 size: how many elements the array will hold

Examples:
float float_numbers[];
char last_name[40];

int sample[10]; 0 1 2 3 4 5 6 7 8 9
19 0 1 4 9 16 25 36 49 64 81
Cont…
Example: Loading and accessing the array sample with the numbers 0 through 9
#include<iostream>
int main() {
int sample[10]; // reserves for 10 integers
int t;
for(t=0; t<10; t++) // initialize the array
{
cout << t << ' '; // display the index
}
cout<<endl;
for(t=0; t<10; t++)
{
sample[t] = t*t;
// display the array
cout << sample[t] << ' ';
}
return 0; }
20
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.

To declare a two-dimensional integer array two_ dim of size 3, 4 we


would write:

int test[3][4];
This corresponds to a table with 3 rows and 4 columns(for example).

21
Cont…
We can generate the array above by using this program:

#include<iostream>
int main()
{

int test[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

for(int i=0;i<3;i++) {
for(int j=0;j<4;j++)
{
cout<<"test["<<i<<"]["<<j<<"]="<<test[i][j]<<endl;
}
}
return 0;
}

22
Writing Format to Two -Dimensional Array Initialization

 The Writing format of two -dimensional array initialization are the same

way as one dimensional arrays.

 For example, the following code fragment initializes an array squares with the

numbers 1 through 10 and their squares:


int squares[10][2] ={ 1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64
9, 81
10, 100};
23
Cont…
 For better readability, one can use sub aggregate grouping by

adding braces accordingly.

 The same declaration as above can also be written as:

int squares[10][2] = { {1, 1},{2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49},
{8, 64}, {9, 81}, {10, 100}};

24
Arrays of Strings in dimension
 An array of strings is a special form of a
#include <iostream>
two-dimensional array.
#include <cstring>
 The size of the left index determines the
using namespace std;
number of strings.
int main() {
 The size of the right index specifies the char color[4][10] = { "Blue", "Red",
maximum length of each string. "Orange", "Yellow" };
 For example, the following declares an for (int i = 0; i < 4; i++)
array of 30 strings, each having a cout << color[i] << "\n";
maximum length of 80 characters (with return 0;
one extra character for the null }
terminator):

char string_array[30][81];
27
Character Array Initialization
Character arrays that will hold strings allow a shorthand initialization that takes this
form:

char array-name[size] = “string”;

For example, the following code fragment initializes str to the phrase “hello”:

char str[6] = “hello”;


This is the same as writing

char str[6] = {‘h’,‘e’,‘l’,‘l’,‘o’,‘\0’};

Remember that one has to make sure to make the array long enough to include the
null terminator.
28
String Manipulation
Using Arrays

29
Introduction
 String in C++ is a sequence of character in which the last character is the null

character ‘\0’.

 The null character indicates the end of the string.

 Any array of character can be converted into string type in C++ by adding this

special/null character ‘\0’ at the end of the array sequence.

 If a string has n characters then it requires an n+1 element array (at least) to store it.

 Thus the character `a' is stored in a single byte, whereas the single-character string "a"

is stored in two consecutive bytes holding the character `a' and the null character.

30
Cont’d
 A string variable Str1 could be declared as follows:
char Str1[10];
 The string variable Str1 could hold strings of length up to nine characters since

space is needed for the final null character. Strings can be initialized at the time of
declaration just as other variables are initialized.
For example: char str1 [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "Hello";
For example:
char Str1[] = "Hello!";
char Str2[18] = "C++ Programming";
Would store the above two strings as follows:
H e l l O ! \0
Str1
Str2 C + + P r o g r a m m i n g \0

31
String Output

 A string is output by sending it to an output stream, for


example:
char str1=“Hello!”;
cout<< "The string s1 is " << Str1<<endl; //would print
The string Str1 is Hello!
 The setw(width) I/O manipulator can be used before
outputting a string, the string will then be output right-
justified in the field width.

32
String Input
 When the input stream cin is used space characters, n space, tab,
newline etc. are used as separators and terminators.
 To read a string with several words in it using cin we have to call cin.

 To read in a name in the form of first name followed by a last name

char firstname[12], lastname[12];

cout << "Enter First name and Last name: ";


cin >> firstname>> lastname;

cout << "The Name Entered was " << firstname << " " << lastname;

33
Cont…
#include<iostream>
int main() {
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin>>str;
cout<<"You entered : "<<str;
}

34
Cont…
 The cin>> considers a space to be a terminating character &
read strings of a single word.

 To read text containing blanks we use another function,


cin.get().
#include<iostream>
int main()
{
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin.get(str, max);
cout<<"You entered : "<<str;
}
35
Cont…
 Reading strings with multiple lines.
//reads multiple lines, terminates on '$' character
#include<iostream>
int main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<"\n You entered:\n"<<str;
}
Type as many lines of input & enter the terminated character $ when
you finish typing & press Enter.

36
String Constants
 You can initialize a string to a constant value when you define it.
Here's an example'
#include<iostream>
int main()
{
char str[] = "Welcome to C++ programming language";
cout<<str;
}

37
Copying String
 The strings copy performed using strcpy or strncpy function. We assign strings by

using the string copy function strcpy. The prototype for this function is in string.h.

strcpy(destination, source);

 strcpy copies characters from the location specified by source to the location specified by

destination.

 It stops copying characters after it copies the terminating null character.

 The return value is the value of the destination parameter.

 You must make sure that the destination string is large enough to hold all of the

characters in the source string (including the terminating null character).

 strcpy() is a standard library function in C/C++ and is used to copy one string to

another
38
Example:
#include <iostream>
Cont…
#include <string.h>
int main() {
char me[20] = “Dawit";
cout << me << endl;
strcpy(me, "Are You or Not?");
cout << me << endl ;
return 0;
}

 There is also another function strncpy, is like strcpy, except that it copies only a

specified number of characters.

strncpy(destination, source, int n);

 It may not copy the terminating null character.

 C++ strncpy() function , The strncpy() function in C++ copies a specified

bytes of characters from source to destination.


39
Cont…
Example strcpy(one, str2);
#include <iostream> cout << one << endl;
#include <string.h> }
void main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
40
Concatenating Strings
 In C++ the + operator cannot normally be used to concatenate string, as it

can in some languages such as BASIC; that is you can't say


Str3 = str1 + str2;

 You can use strcat() or strncat

 The function strcat concatenates (appends) one string to the end of another string.

strcat(destination, source);
 The first character of the source string is copied to the location of the terminating null

character of the destination string.

 The destination string must have enough space to hold both strings and a terminating null

character.
41
Cont…
Example: char str2[] = "xyz";
#include <iostream> strcat(str1, str2);
#include <string.h> cout << str1 << endl;
void main() str1[4] = '\0';
{ cout << str1 << endl;
char str1[30]; }
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;

42
Cont’d
 The function strncat is like strcat except that it copies only a
specified number of characters.
strncat(destination, source, int n);
 It may not copy the terminating null character.
Example:
#include <iostream> cout << str1 << endl;
#include <string.h> char str2[] = "xyz";
int main() { strcat(str1, str2);
char str1[30]; cout << str1 << endl;
strcpy(str1, "abc"); str1[4] = '\0';
cout << str1 << endl; cout << str1 << endl;
strncat(str1, "def", 2); }
str1[5] = '\0';

43
Comparing Strings
 Strings can be compared using strcmp or strncmp functions.
 The function strcmp compares two strings.
strcmp(str1, str2);

44
Cont’d
Example:
#include <iostream>
#include <string.h>
void main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
}

45
Cont
 The function strncmp is like strcmp except that it compares only a specified number

of characters.

strncmp(str1, str2, int n);

 strncmp does not compare characters after a terminating null character has been
found in one of the strings.
 Example:
#include <iostream.h>
#include <string.h>
int main() {
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
46
Part -II

Structures

47
Structure
 In C++ arrays allows you to define variables that combine several data items

of the same kind but structure is another user defined data type which allows
to combine different data items of different kinds.

 The term structure in C++ means both a user-defined type which is a


grouping of variables as well as meaning a variable based on a user-defined
structure type.

 A structure definition is auser-defined variable type which is a grouping of

one or more variables.

 The type itself has a name, just like int, double, or char but it is defined by

the user and follows the normal rules of identifiers.


48
Cont
 A structure definition is agrouping of several types: it is a group of one or

more variables.

 Before creating astructure variable you must create astructure definition.

 This is a blue print for the compiler that is used each time you create a

structure variable of this type.

 The structure definition is a listing of all member variables with their

types and names.

 When you create a structure variable based on a structure definition, all of

the member variables names are reserved.

 The only nameyou haveto giveis that of the new structure variable.

49
2.Declaration of Structures
 the keyword ‘ struct ’ is used to declare structure.
Example
 syntax for a structure definition:

struct structure-name {
datatype1 variable1;
datatype2 variable2;
Datatype3 variable3;
};

 Creating the object of structure.

 struct structure-name var1, var2, var3….

50
Cont….
 The datamembers(synonym for member variables) of astructure won‟t actually

be created until avariable based on the structure is created.

 Example: The follow defines a structure called ‘date' which contains three

„int‟ member variables:„day‟,„month‟,and„year‟:


struct date {
int day;
int month;
int year;
};
struct date{
int d a y , month, year;
51 };
3.1.Initializing StructureVariables
⚫ You cannot initialize member variables in the structure definition. This is because

that definition is only a map, or plan, of what a variable based on this type will be
made of.

⚫ You can, initialize the member variables of a structure variable. that is, when you
create a variable based on your structure definition you can pass each member
variable an initializer.

⚫ To initialize a structure variable‟s members, you follow the original declaration

with the assignment operator (=).

⚫ Next you define an initialization block which is a list of initializers separated

by commas and enclosed in curly braces.


52
⚫ Lastly, you end it with a semi-colon. These values are assigned to member variables in the order

that they occur.


⚫ Let‟s look at an example:

date nco_birthday = { 19,8,1979 };


student std1={"Ababe", "Scr/2222/22"};

⚫ It is possible to use any expression that you normally would but remember that the expression must

result in a value. Here is an example of initialization with things other than literals:
int myday = 19;
int mymonth = 5;
date nco_birthday = { myday,mymonth + 3,2001 - 22 };

⚫ Although you can assign avalue to avariable in the same way you initialize it, the same is not true

with structures.. So while this works:


int x;
x = 0;
53
3.2.Accessing members of a structure variable
 Dot operator [ .] is used to access individual structure element. Simply use the

structure‟s name , follow with the period, and end with the member ;

 Example: to reading and displaying values to and from structure s1.

 cin>>s1.id; //storing to id item of s1


 cin>>s1.name; //storing a name to s1
 cout<<s1.id; //displaying the content of id of s1.
 cout<<s1.name; // displaying name

54 Example: a.roll, a.name, b. marks, cin>>b.roll;


Aprogram that creates student struct and uses it to store student information.
1. #include<iostream>
2. struct student { 14. cin>>s2.name;
3. int id; 15. cout<<"Students Information";
4. char name[15]; 16. cout<<"Student id\t Student Name";
5. };
17. cout<<endl<<s1.id<<"\t"<<s1.name;
6. int main() {
18. cout<<endl<<s2.id<<"\t"<<s2.name;
//creating two studentvariables
19. }
7. student s1,s2;
8. cout<<" Enter Student Id";
9. cin>>s1.id;
10. cout<<"Enter Name";
11. cin>>s1.name;
12. cout<<"Enter Student Id";
13. cin>>s2.id; cout<<"Enter Name";
55
Example 2:This program demonstrates using member variables for user input, output,and mathematical operations.

1. #include <iostream>
2. struct date { 16. cout << “You were born in the“<< ((birth.year / 100) + 1)
3. int day,month,year; << “th Century!”<< endl;
4. }; 17. return 0; }
5. int main() {
6. date birth;
7. cout << “Enter your birth date!”<< endl;
8. cout << “Year:“;
9. cin >> birth.year;
10. cout << “Month:“;
11. cin >> birth.month;
12. cout << “Day:“;
13. cin >> birth.day;
14. cout << “You entered “ << birth.month << “/”<< birth.day << “/”<< birth.year <<
56 endl;
3.3.Variables with Definition
 The syntax of „struct‟ also allows you to create variables based on a structure definition without
using two separate statements:

struct tag {

member(s);

} variable;

 The structure variables created in this way will have the same scope as their structure definition.

 This is a nice thing to use when you want to group some variables in one place in your program
without it affecting other things.

 You can create a structure definition as well as variables from it in that one local place and not have
to ever use it again.

 Example:A„point‟ variable right after the „pointtag‟ structure is defined:

struct pointtag{

int x, y;
57 } point;
 In this, „point‟ is a variable just as if we had declared it separately. In fact, this statement is
identical to:
struct pointtag{
int x,y; };
pointtag point;

 Rather than defining a structure under a name and then creating variables which refer to the named definition,
the definition becomes part of the variable declaration.

 It is evenpossible to omit the structure tagwhich may makemore sense in this situation:

struct{
int x,y;
} point;
 However,like in any variable declaration, you can create multiple variables of the same type by separating them with commas:

struct{

int x,y;

} point1 = { 0,0},point2 = {0,0};


58
4. Array of struct
We can create an array of structures. Thus we can use the same structure for more than
one variables which adds more flexibility to your program.

}
59
5. Declaring struct types as part of a struct
⚫ A structure definition contains multiple variables,but not necessarily just primitives.

⚫ Youcandefine astructure to have structure member variables.

⚫ Now if you have data's like birth of date of an employee,published year of abook, address

of aperson.You must be able to incorporate this type of data's in other struct.


struct structname1 {
datatype1 variable1;
datatype2 variable2;
};
struct structname {
datatype1 variable1;
datatype2 variable2;
Structname1 data1;
};
60
cout<<"\nEnter Student Name";
#include<iostream>
cin>>s1.name; cout<<"\n Enter Section";
#include<conio.h>
struct Address{ cin>>s1.section;
int kebele; char //reading address attributes
Kebele_ketema[20]; char cout<<"\nEnter Kebele"; cin>>s1.studaddress.kebele;
roadname[20]; cout<<"\nEnter Street Name";
}; cin>>s1.studaddress.roadname; cout<<"\nEnter
struct Student { Ketema"; cin>>s1.studaddress.ketema; cout<<"\n
int id; Student Information";
char name[15]; cout<<"\n id\t Name\t Section \t Kebele";
char section[ 6];
cout<<" \t S treet N ame \t Ketema ";
//declaring address type within student
cout<<"\n======================";
Address studaddress;
cout<<endl<<s1.id<<"\t"<<s1.name;
};
cout<<"\t"<<s1.section<<"\t"<<s1.studaddress.keb ele;
int main() {
cout<<"\t"<<s1.studaddress.roadname<<"\t";
//creating Student type that encapsulates Address
Student s1; cout<<s1.studaddress.ketema;
cout<<"\n Enter Student Id"; return 0;
cin>>s1.id; }
61
6. Defining Structure in Structure
 It is possible to define a structure inside a structure definition and create
variables from it at the same time. For example:
struct moment {
struct date {
int day,month,year;
} theDate;
struct time {
int second,minute,hour ;
} theTime;
};
 The drawback of the above is that the „date‟ and „time‟ definitions cannot

be used elsewhere without also referring to the parent structure. If the „date‟definition isn‟t going
to be usedelsewhere anyway, the structure tag can simply be omitted.
62
The following program demonstrates how the structure definitions would be written as well as
uses the defined structure types in an extended “birth date” sample:

#include <iostream.h> cin>> birth.theDate.month;


struct date { cout<< "Day:";
int day,month, year; cin>>birth.theDate.day;
}; cout<<"Hour (military):";
struct moment { cin>>birth.theTime.hour;
date theDate; cout << "Minute:";
struct {
cin >> birth.theTime.min;
int sec,min,hour; cout<< "Second:";
} theTime;
cin >> birth.theTime.sec;
};
cout << "You entered"<<birth.theDate.month<<
int main() {
"/"<<birth.theDate.day<< "/" <<birth.theDate.year<<" @
moment birth;
cout<<"Enter your birth moment!" << endl; cout<< "<<birth.theTime.hour<< ":"

"Year:"; <<birth.theTime.min<<":"<<birth.theTime.sec<< endl;

cin>> birth.theDate.year; cout<< if (birth.theTime.hour > 20 ||birth.theTime.hour < 8) cout << "You

"Month:"; were born early in the morning!" << endl;

return 0;} 63
User Defined Data Types (UDT)
 The UDT is a typical data type that we can derive out of any existing data type in
a program.
 A UDT is a data type that you derive from existing data types, but is still
considered to be separate and incompatible from them.
 UDTs enable you to extend the built-in types already available in and create your
own customized data types.
 Class : A User-defined data type that holds data members and functions whose
access can be specified as private, public, or protected.
 It uses the 'class' keyword for defining the data structure.
 Structure : A structured data type is used to group data items of different types
into a single type.

64
C++ Union
 A union is a user-defined data type that allows you to store different data types in the same memory
location.
 Unlike structures, which allocate memory for all members, unions share memory among their
members.
Syntax of Union in C++
Union is defined using the ‘union’ keyword.
// Defining a union variable

#include <iostream> union geek student1;


// Assigning values to data member of union geek and
using namespace std;
// printing the values of data members
// Creating a union
student1.age = 25;
union geek { // Defining data members
cout << "Age : " << student1.age << endl;
int age;
student1.grade = 'B';
char grade; cout << "Grade : " << student1.grade << endl;
float GPA; }; student1.GPA = 4.5;
int main() cout << "GPA : " << student1.GPA << endl;

{ return 0; }
65
66
C++ Enums
oAn enumeration is a user-defined data type that consists of a set of named integer constants.
o It provides a way to create symbolic names for values to improve code readability
oAn enum is a special type that represents a group of constants (unchangeable values).
o To create an enum, use the enum keyword, followed by the name of the enum, and
separate the enum items with a comma:
Define an enumeration for days of the week
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
// Use enumeration constants Days today = Wednesday; if (today == Wednesday) {
std::cout << "It's Wednesday!" << std::endl; }
return 0;
}

67
1. #include <iostream>
Example
2. using namespace std;
3. enum Days { 17. case TUESDAY: cout << "2: Tuesday" << endl; break;
18. case WEDNESDAY: cout << "3: Wednesday" << endl;
4. MONDAY = 1,
break;
5. TUESDAY,
19. case THURSDAY: cout << "4: Thursday" << endl; break;
6. WEDNESDAY,
20. case FRIDAY: cout << "5: Friday" << endl; break;
7. THURSDAY, 21. case SATURDAY: cout << "6: Saturday" << endl; break;
8. FRIDAY, 22. case SUNDAY: cout << "7: Sunday" << endl; break;
9. SATURDAY, 23. }

10. SUNDAY 24. }

11. };
12. int main() {
13. // Loop through days 1 to 7 and display them
14. for (int i = MONDAY; i <= SUNDAY; i++) {
15. switch (i) {
16. case MONDAY: cout << "1: Monday" <<
endl; break; 68
Case Study 1:

Write a C++ program for student information registration


system based on the given specification. The Program should
accept the Student Id, full name, sex, Birth date and address. The
birth date should have day, Month and year and the address also
should have Kebele, Kefele ketema, and road name. Your program
must register a (15) student and finally display the recorded
Student information to user.

69
Thank You
chew
See you next!
2017 E.C
70

You might also like