Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

Programming with C++

CSC 204 / Computer Science

Dr. D. O. Aborisade

1
Recommended Materials:
Schaum's Outline of Programming with C++ 2nd Edition by John Hubbard

Federal University of Agriculture, Abeokuta


2
Compound Data types in
C++
This module introduces Compound Data types in C++. At the end of this module,
students will be able to:
(i) explain correctly what Compound Data types is in C++
(ii) enumerate Compound Data types in C++
(iii) explain and create Arrays with C++ programs

Federal University of Agriculture, Abeokuta, Nigeria. 3


Compound Data types ?
• A Compound data type is a data type that is defined in terms of
another type e.g
• Array
• Object references
• Pointers
• While fundamental data types are:
• int
• Float
• Double
• char
• wchar
• bool
Array in C++?
• An Array is a collection of similar data items (or elements) organised un
contiguous memory location that can be referenced using index of a
unique identifier.
• An array is a programing concept that makes handling of large volume
data possible.

age

• An array can be logically represented as shown, where each cell is


created to store or accept an element, and its given an index value.

Federal University of Agriculture, Abeokuta


5
Declaring Array
• An array can be declared using with a statement such as:
type name [elements];
type name [elements][elements];
type name [elements][elements][element][element];

e.g int age[3];


int age[3][5];
char name[10][100][1000][5];

Federal University of Agriculture, Abeokuta 6


Initializing an Array
By default arrays are assigned values zero when defined as
numeric value and assigned empty when defined as char.
To initialize array we use ;
type name [n ]= {val1, val2,…..valn};
or
type name [ ]= {val1, val2,…..valn};
e.g
int age [4 ]= {20, 50, 60, 30};
Or int age [ ]= {20, 50, 60, 30}; which will create an
array such20 as: 50 60 30

Federal University of Agriculture, Abeokuta. 7


Accessing Array
• The values of any of the elements in an array can be accessed just like the
value of a regular variable of the same type. The syntax is:
name[index value];
e.g age[2]; or myage =age[2]; where

age[0] age[1] age[2] age[3]


20 50 60 30

For two-dimensional array


age[2,5]; or myage =age[2,5];

Federal University of Agriculture, Abeokuta. 8


Array-Sample program1
#include <iostream>
#include <string>
using namespace std;
int main() {
int age[5] = {20, 15, 35,45,40};
cout << age[4];
return 0;
}

Federal University of Agriculture, Abeokuta 9


Array-Sample program2
#include <iostream>
#include <string>
using namespace std;
int main() {
string names[4] = {"SAMUEL", "FATI", "SOLA", "TADE"};
cout << names[0];
for(int i = 0; i < 4; i++) {
cout << i << ": " << names[i] << "\n";
}
return 0;
} Federal University of Agriculture, Abeokuta
10

You might also like