0% found this document useful (0 votes)
11 views

BUE - Programming Lec 4 - Arrays 1D

Uploaded by

eng.sara.elmasry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

BUE - Programming Lec 4 - Arrays 1D

Uploaded by

eng.sara.elmasry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

24CPES20/

24COMP02C
PROGRAMMING
AND SOFTWARE
DESIGN

LECTURE 4
1
QUOTE
OF THE
DAY
2
3
AGENDA

• Iteration: For Loop


• 1D Arrays

4
LOOPS
(FOR LOOP)

5
FOR LOOP

for (initialization; condition; increment)


statement;

for (initialization; condition; increment)


{
statement1;
statement2;
}
Repeat statements for a specified number of times.
Parameters are separated using ;

6
Iteration: for Loop
for(start_count; bool_expression; action)
statement;

Any of them can be


empty statement

head: how many


times to repeat
body…track variable
i values
body: part
of code
that is
repeated

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

Find the mistake!

13
Iteration: for Loop (cont.)
Example3

This is a compound body.

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.

for ( ; ; ) Equivalent while (true)


{ {
// Do something // Do something
} This is better }
18
(a) (b)
EXERCISE: TRACE

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.

• Consecutive group of memory locations of the same


name , size and type (int, char, etc.)

25
ARRAYS

26
What is an Array?

What is a dimension?

one dimensional array

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

5th element at position 4


Position number of the
element within array c 28
DECLARING ARRAYS
• When declaring arrays, specify
– Type
– Name
– Number of elements (size)

type arrayName[arraySize];
int c[21]; // array of 21 integers
float d[324]; // array of 324 floats

• Declaring multiple arrays of same type


– Use comma separated list, like regular variables
int b[100], x[27];
29
EXERCISE
*

Declaration ?? float myList[10];


myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
5th Element??
myList[3] 13.2
myList[4] 65.3
5th Array myList[5] 34.33 5th
element Element
at index 4 myList[6] 34.0
value
myList[7] 45.45

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

For example, the following code is illegal:


int size = 4;
double myList[size];

The size should be constant, the following code is correct:


const int size = 4; //must be initialized in the same line
31
double myList[size];
Declaration and Initialization
Declaration
type var_name[size]; → allocates memory
Value or
Constant or
Expression →
constant
NOT variable

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.

void main() Initialize all array elements to 0 using for


{ loop. Note that the array has elements
int arr[5]; arr[0] to arr[4].
Note: Initializing to Zero can also be done
as follows: int arr[5]={0};
for (int i = 0; i < 5; i++)
arr[i] = 0; Print array elements.

for (int i = 0; i < 5; i++)


cout<< arr[i] << endl;

}
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};

float myList[4] = {1.9, 2.9, 3.4, 3.5};


This shorthand notation is equivalent to:
float myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

– If not enough initializers, rightmost elements set to 0


– If too many, gives an error

39
INITIALIZING ARRAYS:
METHOD 1

40
CAUTION

Using the shorthand notation, you have to declare


and initialize the array all in one statement. Splitting
it would cause a syntax error.
For example, the following is wrong:
float myList[4];
myList = {1.9, 2.9, 3.4, 3.5};

float myList[4] = {1.9, 2.9, 3.4, 3.5};

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:

int list[2], myList[2];


………………………….// rest of code
for (int i = 0; i < 2; i++)
list[i] = myList[i];

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];

char grade[6]= {'B','A','A','C','D','D'}; Correct

char letter[6]= {'B','A','A','C'}; Correct

int grade[9];
for ( int i = 0; i <= 9; i++ ) Wrong
cin >> grade[i];
46
EXERCISE
C++ Code Correct?

int numbers[2] = {11, 33, 44}; Wrong

int numbers[1];
Wrong
numbers = 34;

float numbers[0]; Wrong

float price[]= {33.5, 25, 56, 77.25}; Correct

47
*

EXERCISE: OUTPUT?

The rand() function is


used in C/C++ to
generate random
numbers in the range
[0, RAND_MAX) at least
32767

Rand() % n generates numbers from 0 up to (n-1)

Output: Random numbers from 0 to 99

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];

1st, 2nd, 3rd, 4th, After


init i=1 i=2 i=3 i=4
0 0 0 0 11
values[0] 0

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).

const int size = 10;


int numbers[size]={51,24,73,44,25,16,37,88,29,60};
int sum = 0;

for (int i = 0; i < size; i++)


sum += numbers[i];

cout<< "Sum: "<< sum << endl;


51
PROBLEM : SUM ARRAY
ELEMENTS
• Compute the sum of the elements entered by user.
const int size = 5;
int numbers[size];
int sum = 0;

for (int i = 0; i < size; i++)


{
cout << "Enter a new number: ";
cin >> numbers[i];
sum += numbers[i];
}
cout<< "Sum: "<< sum << endl;
52
*

PROBLEM : AVERAGE OF
ARRAY ELEMENTS
• Compute the average of the elements entered by user.
const int size = 5;
int numbers[size];
int sum = 0;

for (int i = 0; i < size; i++)


{
cout << "Enter a new number: ";
cin >> numbers[i];
sum += numbers[i];
}
cout<< "Sum: "<< sum << endl;
int average = sum / size; mistake?
cout<< "Average: "<< average << endl;
53
REMEMBER THE OPENING
PROBLEM:
NUMBERS ABOVE AVERAGE
• Read one hundred numbers, keep their values.
• First, compute their average. Second, find out how
many numbers are above the average.

54
SOLUTION
const int size = 100;
int numbers[size];
int sum = 0;

for (int i = 0; i < size; i++)


{
cout << "Enter a new number: ";
cin >> numbers[i];
sum += numbers[i];
}
float average = (float) sum / size;

int count = 0; // The number of elements above average


for (int i = 0; i < size; i++)
if (numbers[i] > average)
count++;

cout << "Average is: " << average << endl;


cout << "Number of elements above the average: " << count << endl;
55
56

You might also like