Previous Lecture Lecture 7 Next Lecture

Lecture 7, Tue 07/24

Arrays and Number Representations

Arrays

Computer Memory Illustration

Computer Memory

Declaring Arrays

int a[10];
cout << sizeof(5) << endl; // 4 (int)
cout << sizeof(11.1) << endl; // 8 (double)

char b = 'b';
cout << sizeof(b) << endl; // 1 (char)
int a[10];
cout << sizeof(a) << endl; // 40

Bracket Syntax

int a[100];
for (int i = 0; i < 100; i++) {
	cout << a[i] << endl;
}

Example of reading / writing values from / to the array

a[0] = 1;
a[1] = -5;
a[1] = a[0]; // fetching and storing array values
int a[10];
cout << "Enter a number: ";
cin >> a[0];
cout << "a[0] = " << a[0] << endl;
void passArrayValueExample(int x) {
	cout << “Parameter value: “ << x << endl;
}

int main() {
	int x[1];
	x[0] = 3;
	passArrayValueExample(a[0]); // prints 3
}

Example of iterating through the entire array

int a[10];
for (int i = 0; i < 10; i++) {
	a[i] = i; // initializes elements using i
}
int x = a[5] + 2;
cout << x << endl; // 7

Shorthanded way to declare and initialize arrays

char grades[] = {‘A’, ‘B’, ‘C’, 'D', 'F'};

Memory addresses of array elements

Array address

Number Representation

Converting values in different bases to base 10

1 * 52 + 1 * 51 + 0 * 50

= 25 + 5 + 0

= 30

1 * 23 + 1 * 22 + 0 * 21 + 1 * 20

= 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1

= 13

24 = 16

Converting base 10 to binary (base 2)

Decimal to Binary

Hexadecimal Numbers

Hex Value 	Binary Value
0 		0000
1 		0001
2 		0010
3 		0011
4 		0100
5 		0101
6 		0110
7 		0111
8 		1000
9 		1001
A 		1010
B 		1011
C 		1100
D 		1101
E 		1110
F 		1111

116 = 0001

316 = 0011

C16 = 1100

0x13C = 0001001111002

0001,0011,1100

= 13C16