BUE - Programming Lec 4 - Arrays 1D
BUE - Programming Lec 4 - Arrays 1D
24COMP02C
PROGRAMMING
AND SOFTWARE
DESIGN
LECTURE 4
1
QUOTE
OF THE
DAY
2
3
AGENDA
4
LOOPS
(FOR LOOP)
5
FOR LOOP
6
Iteration: for Loop
for(start_count; bool_expression; action)
statement;
7
Iteration: for Loop (cont.)
for(start_count, bool_expression, action)
statement; start_count
if bool_exp is true
{ execute body
index update
re-evaluate bool_exp
}
else
exit the loop
1 2 4
8
1
2 // Counter-controlled repetition with the for structure
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
Output:
7 1
2
8 // function main begins program execution 3
9 void main() 4
5
10 { 6
11 // Initialization, repetition condition and incrementing 7
8
12 // are all included in the for structure header. 9
10
13
14 for ( int counter = 1; counter <= 10; counter++ )
15 cout << counter << endl;
16
17 } // end function main
9
FOR LOOP: COUNT DOWN
int main()
{
for (int i = 10; i > 0 ; i--)
cout << i << '\t';
cout << "FIRE!!\n";
return 0;
}
10
Iteration: for Loop (cont.)
Example1
11
Iteration: for Loop (cont.)
Remark
Index update (IN LOOP HEAD) MUST change the result of
the bool_exp so we can exit the loop at some point of
execution, otherwise you will go into an infinite loop…
something very bad!
12
Iteration: for Loop (cont.)
Example2
13
Iteration: for Loop (cont.)
Example3
14
1
2 // Sum even integers in range from 2 to 100
3 #include <iostream>
4
5 using namespace std;
6 Sum is 2550
7
8 // function main begins program execution
9 void main()
10 {
11 int sum = 0; // initialize sum
12
13 // sum even integers from 2 through 100
14 for ( int number = 2; number <= 100; number += 2 )
15 sum += number; // add number to sum
16
17 cout << "Sum is " << sum << endl; // output sum
18 } // end function main
15
PROBLEM: PRODUCT OF
NUMBERS
• Calculate product of odd numbers from 1 to 15.
void main()
{
int product = 1;
for (int i = 1; i <= 15; i = i+2)
product *= i;
cout << "Product: " << product << endl;
}
16
NOTE
• In for loop, the initialization and increase fields are optional. They can remain
empty, but in all cases the semicolon signs between them must be written.
• For example we could write:
for ( ; n<10 ; n++)
if we wanted to include an increase field but no initialization (maybe
because the variable was already initialized before).
for ( ; n<10 ; )
if we wanted to specify no initialization and no increase.
17
NOTE
• If the condition section in a for loop is omitted, it is implicitly
evaluated to true.
• Thus the statement given below in (a), which is an infinite loop,
is correct.
• However, it is better to use the equivalent loop in (b) to avoid
confusion.
int k =3; j k m
3 2
int m =2;
3 6
for (int j=3 ; j <=10; j=j+m)
5 11
k = k + j; 7 18
k = k * 3; 9 27
11 81
Remember to include
necessary braces
19
EXERCISE: TRACE
j k m
3 2
int k =3;
3 6
int m =2; 18
for (int j=3 ; j <=10; j=j+m) 5 23
{ 69
7 76
k = k + j;
228
k = k * 3; 9 237
} 711
11
20
RECOMMENDATION
• In general, a for loop may be used if the number of repetitions is counter-
controlled, as, for example, when you need to do a process 100 times.
• A while loop may be used if the number of repetitions is sentinel-
controlled, which means use an input value to signify the end of the loop. As
in the case of reading the numbers until the input is 0.
• A do-while loop can be used if the loop body has to be executed before
testing the continuation condition.
21
22
1D ARRAYS
23
OPENING PROBLEM
• Read one hundred numbers, keep their values,
compute their average, and find out how many
numbers are above the average.
Ideas?
24
SINGLE-DIMENSIONAL ARRAYS
• Array is a data structure that represents a collection
of the same type of data.
25
ARRAYS
26
What is an Array?
What is a dimension?
27
ARRAYS
• The array elements are Name of array (Note that
all elements of this array How
accessed through the index. have the same name, c) many
elements
in array c
• Array indices are 0-based. c[0] -45
6
?
c[1]
c[2] 0
• N-element array c c[3] 72
c[4] 1543
c[ 0 ], c[ 1 ] … c[ n - 1 ] c[5] -89
c[6] 0
Nth element at position N-1 c[7] 62
c[8] -3
Example: c[9] 1
c[10] 6453
2nd element at position 1 c[11] 78
type arrayName[arraySize];
int c[21]; // array of 21 integers
float d[324]; // array of 324 floats
myList[8] 99.993
myList[9] 111.23
30
DECLARING ARRAYS
• C++ requires that the array size used to declare an array
must be a constant expression.
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
32
ARRAY ELEMENTS
int c[10];
• To refer to an element
– Specify array name and position number (index)
– Format: arrayname[positionNumber]
• After an array is created, an array element can be used
in the same way as a regular variable.
– Assignment , reading and printing for an integer array c
cin >> c[0]; // set value entered by user to first array element
cout << c[9]; // display the 10th array element
c[2] = 11; // set the 3rd array element to 11
myList[2] = myList[0] + myList[1]; // add 1st and 2nd elements
33
EXERCISE: DIFFERENCE BETWEEN
INDEX/SUBSCRIPT AND SIZE?
Array size
double grades[10]; = number
of
elements
Position/ cout << grades[0]; (Const)
index of
array
element grades[9] = 97.5;
(can be
variable)
cin>> grades[2];
34
NO BOUND CHECKING
int myScores[10];
• C++ does not check array’s boundary.
• So, accessing array elements using subscripts beyond the boundary
(e.g., myScores[10] and myScores[11]) does not cause syntax errors,
but causes undefined behavior. It may appear to work just fine, but
you shouldn't be relying on its safety. ➔RUNTIME ERROR
35
INITIALIZING ARRAY
• When an array is created, its elements are assigned with arbitrary
values.
• Therefore, Before using the array, you must initialize itsy elements
by:
1. Explicitly setting values or
2. Reading user input values into array elements.
36
INITIALIZING ARRAY: METHOD 1
Declare a 5-element array of integers.
}
37
INITIALIZING ARRAY:
METHOD 1
Declare a 5-element array of integers.
int main()
{
Initialize all array elements to 23 using for
int arr[5]; loop. Note that the array has elements
arr[0] to arr[4].
for (int i = 0; i < 5; i++)
arr[i] = 23; //cin>>arr[i];
Print array elements.
for (int i = 0; i < 5; i++)
cout<< arr[i] << endl;
return 0;
}
38
INITIALIZING ARRAYS:
METHOD 1
• Initializer list
– Declaring and initializing in one step:
int n[5] = {14, 22, 63, 24, 15};
39
INITIALIZING ARRAYS:
METHOD 1
40
CAUTION
41
INITIALIZING ARRAYS
• You can omit the array size when you declare the array
using initializers
int n[] = {14, 22, 63, 24, 15};
– 5 initializers, therefore 5 elements in array
• This is also accepted:
int n[5] = {14, 22, 63};
And will auto-initialize the last two elements to zeroes.
• But this will give a syntax error :
int n[2] = {14, 22, 63};
➔ “Too Many initializers” Error
42
INITIALIZING ARRAYS:
METHOD 2
User enters values of array elements.
void main()
{
int arr[5];
cout<<"Enter Array Elements: "<<endl;
for (int i = 0; i < 5; i++)
cin>> arr[i];
cout<<"Displaying Array Elements: "<<endl;
for (int i = 0; i < 5; i++)
cout<< arr[i] << endl;
}
43
COPYING ARRAYS
Can you copy array using a syntax like this?
int myList[2]={1,2} , list[2];
list = myList;
This is not allowed in C++.
You have to copy individual elements from one array to the other
as follows:
44
*
EXERCISE: OUTPUT?
const int arraySize = 10;
int s[arraySize]; // array s has 10 elements
for ( int i = 0; i < arraySize; i++ ) // set array values
s[i] = 2 + 2 * i;
for (int i = 0; i < arraySize ; i++) // Display array values
cout<< s[i] << ", ";
45
EXERCISE
C++ Code Correct?
int arraySize = 5;
Wrong
float numbers[arraySize];
for ( int i = 0; i < arraySize; i++ )
cin >> numbers[i];
int grade[9];
for ( int i = 0; i <= 9; i++ ) Wrong
cin >> grade[i];
46
EXERCISE
C++ Code Correct?
int numbers[1];
Wrong
numbers = 34;
47
*
EXERCISE: OUTPUT?
48
*
EXERCISE: OUTPUT?
Syntax Errors
because constant
identifier must be
initialized when
declared
49
EXERCISE: OUTPUT?
int values[5]= {0}; // set all elements to 0
for (int i = 1; i < 5; i++)
values[i] = i + values[i-1];
values[0] = values[1] + values[4];
values[1] 0 1 1 1 1 1
values[2] 0 0 3 3 3 3
values[3] 0 0 0 6 6 6
values[4] 0 0 0 0 10 10
50
PROBLEM: SUM ARRAY
ELEMENTS
• Compute the sum of the elements of a
hardcoded array (initialized in the code).
PROBLEM : AVERAGE OF
ARRAY ELEMENTS
• Compute the average of the elements entered by user.
const int size = 5;
int numbers[size];
int sum = 0;
54
SOLUTION
const int size = 100;
int numbers[size];
int sum = 0;