Chapter-2 (2)
Chapter-2 (2)
2
Outlines
Homogeneous and heterogeneous data types
Multidimensional arrays
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.
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
then the positive index into the array. The index is specified by
square brackets, [].
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:
{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 [ ],
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.
15
Accessing and processing array elements
To access individual elements, index or subscript is used.
element has an index, which is one less the size of the array
(i.e. arraysize-1).
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
17
1. #include<iostream> Cont…
2. int main() {
6. cout<<numbers[3]<<endl;
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
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.
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
For example, the following code fragment initializes an array squares with the
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:
For example, the following code fragment initializes str to the phrase “hello”:
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’.
Any array of character can be converted into string type in C++ by adding this
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
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.
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.
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.
You must make sure that the destination string is large enough to hold all of the
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
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
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 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 type itself has a name, just like int, double, or char but it is defined by
more variables.
This is a blue print for the compiler that is used each time you create a
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;
};
50
Cont….
The datamembers(synonym for member variables) of astructure won‟t actually
Example: The follow defines a structure called ‘date' which contains three
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.
⚫ 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
structure‟s name , follow with the period, and end with the member ;
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.
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;
}
59
5. Declaring struct types as part of a struct
⚫ A structure definition contains multiple variables,but not necessarily just primitives.
⚫ Now if you have data's like birth of date of an employee,published year of abook, address
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:
cin>> birth.theDate.year; cout<< if (birth.theTime.hour > 20 ||birth.theTime.hour < 8) cout << "You
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
{ 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. }
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:
69
Thank You
chew
See you next!
2017 E.C
70