0% found this document useful (0 votes)
5 views50 pages

CHAPTER - 4 Compound Data Types

This lecture covers compound data types in C++, focusing on arrays, character sequences, pointers, dynamic memory, and data structures. It explains the declaration, initialization, and access of one-dimensional and multidimensional arrays, along with examples and common operations. Additionally, it discusses string manipulation and dynamic memory allocation using pointers.

Uploaded by

lielinazena.1
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)
5 views50 pages

CHAPTER - 4 Compound Data Types

This lecture covers compound data types in C++, focusing on arrays, character sequences, pointers, dynamic memory, and data structures. It explains the declaration, initialization, and access of one-dimensional and multidimensional arrays, along with examples and common operations. Additionally, it discusses string manipulation and dynamic memory allocation using pointers.

Uploaded by

lielinazena.1
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/ 50

Lecture - 4

Compound Data Types


Outline

▪ Arrays

▪ Character Sequence

▪ Pointers

▪ Dynamic Memory

▪ Data Structures
2
Introduction
➢An array is a collection of elements of the same data type stored in
contiguous memory locations.

➢ Array is a kind of data structure that can store fixed size(finite)


sequential collection of homogeneous element.

➢C++ supports the following data types:


✓Primary or Built-in or Fundamental data type
✓Derived data types
✓User-defined data types 3
…continued
➢ Compound data types (a.k.a composite data types) are
data types that can be constructed from fundamental data types
(other compound data types).

➢ Each compound data type has its own unique properties as well.
syntax
data_type array_name[size];
Example:
4
int numbers[5]; // Declares an integer array with 5 elements.
…continued
…continued

➢ Some invalid array declaration:


int v [0]; float v[0.5]; Float v[-90]; Char v[$];

➢ Array Initialization:
Data-type array-name[expression]={elemnt1,elmnt2,…elm-n};
Eg:- int num[5]={0,1,2,3,4};
Float v[4]={0.5,1,1.5,-4,};
Char sex[2]={‘M’ , ’F’};
Char name[5]={‘R’ , ‘ a ’ , ‘ v ’ , ‘i’ , ‘ c ’}; 6
Accessing array elements
➢ How can we insert lists of arrays ?

➢ How can we display the inserted arrays?

➢ Coping Arrays:
const int SIZE=10
int x [SIZE] ;
int y [SIZE] ;
for (int i = 0 ; i < SIZE; i++) // Loop to do copying, one element at a time
x[i] = y[i];
7
Introduction to Array
➢ For example 1 , an array to contain 5 integer values of type int called
foo could be represented like this

➢where each blank panel represents an element of the array.


➢ These elements are numbered from 0 to 4, with 0 being the first while
4 being the last.
➢In C++, the index of the first array element is always zero. 2
Introduction to Array
➢For example : Suppose a class has 27 students, and we need to store the
grades of all of them.
➢Instead of creating 27 separate variables, we can simply create an array.
➢Like a regular variable, an array must be declared before it is used.
➢A typical declaration for an array in C++ is:

Type array_Name [ size ];

➢ typical declaration for the above examples:


✓example 1 => int foo[5];
✓example 2 => double grade[27];
2
Types of Array

➢One Dimensional Array


➢Multidimensional arrays
Types

1
0
11
One Dimensional Array
➢ It stores elements in a single dimension. And, in this array a single
specification is required to describe elements of the array.
➢ The diagram below shows that it arranged all the elements in row wise
in a single dimension, one after other.

➢Below is illustration of array.


12
One Dimensional Array
➢It is a collection of same data types. 1-D array is declared as:
Syntax:
data_type variable_name[size]
✓ data_type is the type of array, like int, float, char, etc.
✓ variable_name is the name of the array.
✓ size is the length of the array which is fixed.
The Size must be an integer constant greater than zero.
Note: The location of the array elements depends upon the data
2
type we use.
13

Example

❖int A[10];
An array of ten integers

❖Char str[20];

▪An array of twenty characters .

❖ int a[ 100 ], b[ 27 ] ;

▪Defining multiple arrays of same type


2
Array Initialization:
➢ We can explicitly initialize arrays at the time of declaration.
➢Syntax:
data_type array_name[size]={value1, value2,……..valueN};
➢Value1, value2, valueN are the constant values known as initializers, which
are assigned to the array elements one after another.
▪Example:
▪Define an array temperature of 5 elements contains float numbers , and
Initialize it with these numbers : 12.3 , 7.5 , 65 , 72.1, 87.5 .
2
15

Array Initialization:
➢ double temperature [5] = {12.3 , 7.5 , 65 , 72.1, 87.5 };

temperature [0] 12.3

temperature [1] 7.5

temperature [2] 65.0 Elements

temperature [3] 72.1

temperature [ 4 ] 87.5

Index
16

Array Initialization:
➢ int N[ ] = { 1, 2, 3, 4, 5 };
In 1-D arrays it is optional to specify the size of the array. If size is omitted
during initialization then the compiler assumes the size of array equal to the
number of initializers.
➢ int N[5] = { 0 } ; // the first element of the array is being initialized to 0.
➢ int B[20] = {2, 4, 8, 16, 32};
Unspecified elements are guaranteed to be zero .
If not enough initializers, rightmost elements become 0 .
➢ int C[4] = {2, 4, 8, 16, 32};
Error — compiler detects too many initial values .
17

Accessing Array Element:


❖An individual element within array is accessed by use of a subscript

(index) that describes the position of an element in the array , it must be

an integer or integer expression .

➢We can’t copy the elements of one array to another array by simply

assigning it.

➢ Example: int a[5]={9,8,7,6,5}; and int b[5]; b=a; //not valid


➢ we have to copy all the elements by using for loop.
➢ Sizeof operator used to show memory allocation of the given
Array element using Sizeof(array name);
18
Accessing Array Element Example:

The symbol table for the program


Variable Name Address Value a
Out put
a 0x7ffe58e7cc4 7
19
Array Initialization:
Const int SIZE=10 ➢x = y ; // Error - Illegal
int x [SIZE] ;
int y [SIZE] ;
➢Only individual elements can be assigned to using the index operator,
➢e.g., x[1] = y[2];
➢To make all elements in 'x' the same as those in 'y' (equivalent to
assignment), a loop has to be used.
for (int i = 0 ; i < SIZE; i++) // Loop to do copying, one element at a time
x[i] = y[i];
➢This code will copy the elements of array y into x, overwriting the
original contents of x.
20
Array Initialization:
1. Write a c++ program that display the elements of the following array
➢Double marks[20]={50,90,30,100,78,68};
2. Write a c++ program that initialize elements for the following array from the user, and
display the values/elements. double scores[5];
3. Write a c++ Program to Increment every Element of the Array by one & Print Incremented
Array for the following array. int array[4] = {100, 200, 300, 400};
4.Write a c++ Program that display the sum of the following array elements
➢ int array[4] = {100, 200, 300, 400};
5. Write a c++ Program to search the element is found in the given array element
6. Write a c++ Program to revers the given array element
7. Write a c++ program to sort the given array element either in ascending
or descending order
21
Array Initialization:
Q? Write a c++ program that display the maximum value from the array
elements.

Q? At what index is
the maximum located
22
Multidimensional arrays
▪ A multidimensional array is an array with more than one dimension.
▪ It is the homogeneous collection of items where each element is
accessed using multiple indices.
▪ A 2D array also falls under the category of a multidimensional array.
▪ MD array can have any number of dimensions.
Data type array_name [size 1][size2]….[size n]
where,
Data_type: Type of data to be stored in the array.
Array_Name: Name of the array.
size1, size2,…, sizeN: Size of each dimension.
23
Multidimensional arrays
➢ The size of an array is equal to the size of the data type multiplied by

the total number of elements that can be stored in an array.

➢We can calculate the total number of elements in an array by

multiplying the size of each dimension of a multidimensional array.

➢Here size1, size2 up to sizeN describe the number of dimensions.

➢type array_Name [ x ][ y ];

Int array[3][2] // two dimensional array

int array [5][2][3] // three dimensional array


24
Two-dimensional array
Example: int a[4][5];
➢ Reading values in a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];
➢Displaying values of a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cout<<a[i][j];
25
Two-dimensional array
1. Write a c++ program that display the maximum value from the following
array elements.
int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};
2. Write a c++ program to display the sum of two dimensional array.
int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};
3. Write a c++ program that display the sum of two 2X2 matrices.
int arr1[2][2]
int arr2[2][2]
…continued
Multi-dimensional array initialization
int x[2][2]={1,2,3,4};
X[0][0]=1
X[0][1]=2
X[1][0]=3
X[1][1]=4
int v[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
➢ for the sake of clarity, the program could group the
initializations with braces, as shown below.
int [5][3] = v{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13,
14,15} } 10
…continued

#include<iostream.h>
void main()
{
int SomeArray[5][2] = {{0,0},{1,2}, {2,4},{3,6}, {4,8}}
for ( int i=0; i<5; i++)
for (int j = 0; j<2;j++) {
cout<<"SomeArray["<<i<<"]["<<j<<'']:'';
cout<<endl<<SomeArray[i][ j];}
}
11
…continued
#include<iostream.h>
void main()
{
int v[3][4] = {{1,2,3},{5,6,7}, {9,10,11}}
for ( int i=0; i<3; i++)
for (int j = 0; j<4;j++) {
cout<<v[i][ j]<<“ “;
cout<<endl;}
}
12
Omitting the Array Size:
➢ If a one-dimensional array is initialized, the size can be omitted
as it can be found from the number of initializing elements:

int x[] = { 1, 2, 3, 4} ; //This initialization creates an array


of four elements.

➢ Note however:
int x[][] = { {1,2}, {3,4} } ; // error
is not allowed and must be written
13
int x[2][2] = { {1,2}, {3,4} } ;
Character Sequence/String
➢ String i s 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 by
appending this special character at the end of the array sequence.
✓ Hence if a string has n characters then it requires an n+1 element array
(at least) to store it.
➢ Eg:- char-data-type array-name[exp];
char s1[] = "example“ means |e|x|a|m|p|l|e|\0|
char s2[20] = "another example“ means
|a|n|o|t|h|e|r||e|x|a|m|p|l|e|\0|?|?|?|?|
14
…continued

➢ Eg:- Char name[5]={‘ r ’ , ‘ a ’ , ‘ v ’ , ‘i’ , ‘ c ’};


for(int i=0;i<=4;i++)
Cout<< name[i];
➢ Input/output
Char x[20];
➢ Inserting
• Cin.get(x,20, ‘ \ o ’ )
• Cin>>x;
➢ Display
• Cout<<x;
15
Some string library functions
The string data_type in C++ provides various functionality of string
manipulation.
They are:
strcpy(): It is used to copy characters from one string to another string.
strcat(): It is used to add the two given strings.
strlen(): It is used to find the length of the given string.
strcmp(): It is used to compare the two given string.
16
…continued
Arrays of Strings :
➢ A special form of a two-dimensional array is an array of strings.
➢ It is not uncommon in programming to use an array of strings.
The input processor to a database, for instance, may verify user
commands against a string array of valid commands.
➢ To create an array of strings, a two-dimensional character array
is used,
• with the size of the left index determining the number of strings and
• the size of the right index specifying the maximum length of each
string, including the null terminator.
18
…continued
Eg:- char str_array[30][80];

➢ Accessing an individual string is quite easy: you simply specify


only the left index.

➢ To access an individual character within the third string, you will


use a statement like this:
• gets(str_array[2]);

➢ This displays the fourth character of the third string. 34


• cout << str_array[2][3];
Dynamic Memory & Pointers

➢ The real power of pointers is seen when they are used to point to
dynamically allocated variables.

➢ Dynamic variables are used just like ordinary static variables except:
➢ They are not declared, so they have no identifiers like static variables do.
➢They are created during run time, not when the program is compiled.

35
…continued
➢ Storage for these variables comes from an area of memory called the
free store or the heap.
➢ The creation of new dynamic variables is called memory allocation
and the memory is called dynamic memory.
➢ C++ uses the new operator create a dynamic variable.
▪ Memory in the C++ program is divided into two parts:
▪ Stack: All variables declared inside any function take up the stack's
memory.
▪ Heap: It is the unused memory of the program and can be used to
allocate the memory at runtime dynamically.
21
…continued
Syntax

➢ pointer-variable = new data-type;


int * myIntPtr; // create an integer pointer variable
myIntPtr = new int; // create a dynamic of the size integer

➢ new returns a pointer (or memory address) to the location where the
data is to be stored.

22
Dynamic Array
➢ Allocate entire arrays with the new operator called dynamic arrays.

➢ This allows aprogram to ask for just the amount of memory space it
needs at run time.
Example:
int * myIntPtr;

myIntPtr = new int[4]; // Loading array with value

myIntPtr [1]=135;
23
…continued
➢ The new operator gets memory from the free store (heap).

➢ When you are done using a memory location, it is your responsibility


to return the space to the free store is done with the delete operator.

➢ Pointers should always point to something.

➢When an object pointed to is no longer needed, the memory


should be freed with delete and the pointer should be assigned the
special value null, defined in the stddef.h header file. 39
…continued

delete myIntPtr; // return memory to free store


myIntPtr = null; // point to special “nothing” value.
Delete block of Memory
delete[] pointer-variable;
Example:
// It will free the entire array
// pointed by p.

delete[] p;
40
…continued
Dangling pointer
➢ When you apply delete to a pointer variable, the dynamic
variable it is pointing to is destroyed.
➢ At that point, the value of the pointer variable is undefined,
which means that you do not know where it is pointing, nor what the
value is where it is pointing.
➢ These undefined pointer variables are called dangling pointers.
41
Data Structures
Data structures are ways to organize and store data efficiently to
facilitate operations like searching, sorting, and data manipulation.

➢ A Structure is a collection of related data items, possibly of


different types.
➢ A structure type in C++ is called struct.
➢ A struct is heterogeneous in that it can be composed of data of
different types.
➢ In contrast, array is homogeneous since it can contain only
data of the same type.
42
…continued
➢ Structures hold data that belong together.

➢ Examples:
• Student record: student id, name, major, gender, start year,

• Bank account: account number, name, currency, balance, …
• Address book: name, address, telephone number, …

➢ In database applications, structures are called records. 43


…continued
➢ Individual components of a struct type are called members (or
fields).

➢ Members can be of different types (simple, array or struct).

➢ A struct is named as a whole while individual members are


named using field identifiers.

➢ Complex data structures can be formed by defining arrays of


structs.
44
…continued
struct <struct-type>{
<type> <identifier_list>;
<type> <identifier_list>;
...
} ; //Each identifier defines a member of the structure.
➢ Example:
struct Date {
int day;
int month;
int year;
};
The Date structure has 3 members, day, month & year.
30
…continued
Example 1:-
struct StudentInfo{ int Id;
char Dept[20];
char Name[20];
Char gender;
};
Example 2:-
struct StudentGrade{ char Name[15];
char Course[9];
int Lab[5];
int Homework[3]; int Exam[2]; 31
};
…continued
Accessing structure
➢ Once a structure variable has been defined, its members
can be accessed using something called the dot operator.
Example:
StudentInfo aastu[100];
strcpy(aastu[98].Name,
“Abebe"); aastu[98].Id =
12345;
strcpy(aastu[98].Dept,
“SWEG"); aastu[98].gender =
'M';
aastu[0] = aastu[98];
➢ StudentInfo is a structure defined earlier. 47
…continued

Nested Structure
struct GradeRec {
float percent;
char grade;
};
struct StudentRec{
string lastName;
string firstName;
int age;
GradeRec courseGrade;
};
48
Exercise

➢ Write a program which inserts a set of numbers in a two


dimensional array and display the contents of the array on the
screen?

➢ Write a program using structure to hold student detail


information and print when required?
➢ Expand the first program using function to read student and print the
detail?
49
Summary:

Arrays are useful for storing fixed-size collections.


Character sequences (strings) enable manipulation of text.
Pointers provide direct memory access, enhancing flexibility.
Dynamic memory allows runtime memory allocation for efficiency.
Data structures it optimize data management and algorithms.

50

You might also like