6. Array Initialization
double balance [4] = { 1000.0, 2.0, 3.4, 7.0 };
Presented by TA. Nada Kamel
int bar [5] = { 10, 20, 30 };
int baz [5] = { };
7. Accessing Array Values
The syntax to access a single element in an array is:
arrayName[index]
Presented by TA. Nada Kamel
Example 2
foo[2] = 7; // Intializing index 2 of array foo with 7
Example 1
x = foo[2]; // Storing the value of foo[2] in variable x
cout << x; // Output is 77
8. Accessing Array Values (Cont.)
The syntax to access All values of an array is by using a loop.
int foo [] = {16, 2, 77, 40, 70};
int result=0;
for ( int n=0 ; n<5 ; n++ )
{
result += foo[n];
}
cout << result << endl;
Presented by TA. Nada Kamel
If no value in the square brackets, you
have to initialize the array to have a size in
the memory.
// result = 16+2+77+40+70 = 205
10. Problem 1
Write a C++ program that takes a positive integer value for n (not more than
55) and computes the sum of the following series:
1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + ...... + n
Presented by TA. Nada Kamel
11. int n;
cin >> n;
if (n < 1 || n > 55)
cout << “Please enter a positive number.n”;
else
{
int values[55], sum = 0;
for (int j = 0; j < n; j++)
{
if(j == 0 || j == 1)
values[j] = 1;
else
values[j] = values[j-2] + values[j-1];
sum += values[j];
}
cout << “Sum of value(s) is ” << sum << endl;
}
12. Problem 2
Trace the following code
int j;
int one[5], two[10];
for (j = 0; j < 5; j++)
one[j] = 5 * j + 3;
cout << “One contains: ”;
for (j = 0; j < 5; j++)
cout << setw(5) << one[j];
cout << endl;
for (j = 0; j < 5; j++)
{
two[j] = 2*one[j] - 1;
two[j + 5] = one[4 - j] – 1 + two [j];
}
cout << “Two contains: ”;
for (j = 0; j < 10; j++)
cout << setw(5) << two[j];
cout << endl;
13. Output
One contains: 3 8 13 18 23
Two contains: 5 15 25 35 45 27 32 37 42 47
Presented by TA. Nada Kamel