0% found this document useful (0 votes)
28 views51 pages

(SP - 25) Lecture 1 - 1D Arrays - NOTES

The document outlines a structured programming course focusing on one-dimensional arrays, including course logistics, assessment methods, and available references. It details array declarations, initializations, and operations, emphasizing the importance of understanding array indexing and memory management in C++. Additionally, it includes exercises and problems related to array manipulation and computation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views51 pages

(SP - 25) Lecture 1 - 1D Arrays - NOTES

The document outlines a structured programming course focusing on one-dimensional arrays, including course logistics, assessment methods, and available references. It details array declarations, initializations, and operations, emphasizing the importance of understanding array indexing and memory management in C++. Additionally, it includes exercises and problems related to array manipulation and computation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Structured Programming

Lecture 1
One Dimensional Arrays
Course Logistics
• Instructors
– Dr. Maryam Nabil (Scientific Computing Department)
– Dr. Salsabil Amin (Basic Sciences Department)
• Contact: [email protected]
• Office: 3rd floor, next to Tolba Lecture hall

– Dr. Naglaa Fathy (Information Systems Department)


• Contact: [email protected]
• Office: 2nd floor, below SaeedAbdElwahab Lecture hall

• Credit to Dr. Salma Hamdy, Dr.Yasmin Afify and


Dr. Sally Saad for content preparation

2
Course Material

Google Drive
(will be sent to your admin)
Course Logistics

• Assessment (100 points)


Final Examination 50
Midterm 15
Practical 10
Project 15
Quiz 1 (in lab) 5
Quiz 2 (online) 5
Lecture Bonus +5

4
Course Logistics – Textbook

Available References:
• C++ How to Program, 5th edition, Deitel &
Deitel, Prentice Hall- Pearson Education
International, 2005.
• Competitive Programming, Handbook for
ACM ICPC and IOI Contestants, Steven
Halim, Felix Halim, 2013. (Recommended by the
late Youssef El-Kayyali- ACM Head of
Training Committee)
• Problem Solving with C++, 8th edition,
Walter Savitch, Addison Wesley-Pearson
Education International, 2012.
5
Course Logistics – Outline

1.1D array
2.Functions 1 (by value)
3.Structures+(Project announcement)
4.GUI Support Session+ Problem Solving +(Project Registration)
5.Functions 2 (By Ref) + passing arrays
6.2D array + Problems
7.Pointers I (Concept)
8.Pointers II
9.Recursion
10.Revision

6
Arrays

7
Opening Problem

 Read one hundred numbers, compute their


average, and find out how many numbers are
above the average.

Ideas?

-8-
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 , type (int, char, etc.) and size
(4 bytes, 8 bytes, etc.)

-9-
Arrays

The array elements are accessed through the index.


Array indices are 0-based.
1st element at position 0
4th element at position 3
nth element at position n-1
-10-
What is an Array?

What is a dimension?

one dimensional array


Arrays
Name of array (Note that
all elements of this array
have the same name, c)
How
c[0] -45 many
c[1] 6 elements
in array
c[2] 0
c?
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78

Position number of the


element within array c
-12-
Declaring Arrays

 When declaring arrays, specify


 Type

 Name

 Number of elements (size)

type arrayName[arraySize];
int grades[21]; // array of 21 integers
float numbers[324]; // array of 324 floats

 Declaring multiple arrays of same type


 Use comma separated list, like regular variables

int b[100], x[27];


-13-
*
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
myList[6] 34.0
at index 4 value
myList[7] 45.45

myList[8] 99.993

myList[9] 111.23

-14-
Declaring Arrays

 C++ requires that the array size used to declare an array


must be a constant expression.

For example, the following code is illegal:


int size = 4;
double myList[size]; //Wrong

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


const int size = 4; //must be initialized in the same line
double myList[size]; //Correct

-15-
Constants

• Meaningful name to represent data


const int NUMBER_OF_STUDENTS = 24;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called “named constants” or “read-only” variables

• You can aslo use #define dircetive


#define NUMBER_OF_STUDENTS 24

16
Constants
Const Vs.#define

-17-
Constants
Const Vs.#define

18
Declaration and Initialization
Declaration
type var_name[size]; → allocates memory
Value or
Constant or
Expression
→ constant
NOT variable
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

-20-
Exercise: Difference Between Indices?
Array size
= number
of elements
double grades[10]; (Const)

cout << grades[0];

Position/
index of grades[9] = 97.5;
array
element
(can be
variable) cin>> grades[2];

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

-22-
Initializing Array

• When an array is created, its elements are assigned with


arbitrary values (Garbage).

• Therefore, you must initialize the array elements by:

1. Explicitly setting values or

2. Reading user input values into array elements.

-23-
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

-24-
Initializing Arrays: Method 1

right most
elements are
assigned zero

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

-26-
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

-27-
Initializing Arrays:
Method 2
User enters values of array elements.

int 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;
return 0;
}
-28-
Remember

if an array is declared, but not initialized, all its elements


will contain “garbage”, like all other local variables.

-29-
Copying Arrays

Can you copy array using a syntax like this?


list = myList;
This is not allowed in C++.

You have to copy individual elements from one array to


the other as follows:

const int ARRAY_SIZE = 13;


int list[ARRAY_SIZE], myList[ARRAY_SIZE];
………………………….// rest of code
for (int i = 0; i < ARRAY_SIZE; i++)
list[i] = myList[i];
-30-
*
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; i s[i]
for (int i = 0; i < arraySize ; i++) 0 2+0=2
1 2+2=4
cout<< s[i] << ", ";
2 2+4=6
... ...
9 2+18=20

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

-33-
*
Exercise: Output?

num num%3
6 0
7 1
8 2
9 0
Random numbers from 0 to 99 10 1
11 2
12 0

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

-34-
*
Exercise: Output?

Syntax Errors
because
constant
variable must
be initialized
when declared

-35-
*
Exercise: Output?

int values[5]= {0}; // set all elements to 0


i values[i]
for (int i = 1; i < 5; i++)
1 1+0=1
values[i] = i + values[i-1]; 2 2+1=3
values[0] = values[1] + values[4]; 3 3+3=6
4 4+6=10
1st, 2nd, 3rd, 4th,
init i=1 i=2 i=3 i=4 After
values[0] 0 0 0 0 0 11
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

-36-
Problem: Sum Array Elements

 Compute the sum of the elements of an array.

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;

-38-
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];
}
for (int i = 0; i < size; i++)
sum += numbers[i];
cout<< "Sum: "<< sum << endl;
-39-
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;
-40-
*
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; Problem?
cout<< "Average: "<< average << endl;
-41-
Problem: Numbers Above Average

 Read one hundred numbers. First, compute


their average. Second, find out how many
numbers are above the average.

-42-
Solution
const int size = 100;
float numbers[size];
float sum = 0;

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


{
cout << "Enter a new number: ";
cin >> numbers[i];
sum += numbers[i];
}
float average = 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;
-43-
Linear Search
Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
-44-
Linear Search

 Compare each element of array with key value


 Start at one end, go to other

 Useful for small and unsorted arrays


 Inefficient

 If search key not present, examines every element

-45-
*
Problem: Search Maximum
const int size = 50;
int numbers[size];
int max=0;
Does it work
for negative
for (int i = 0; i < size; i++) numbers?
{
cout<< "Enter number: ";
cin>> numbers[i];
}

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


if (numbers[i] > max)
max = numbers[i];

cout<< "Maximum number: "<< max << endl;


-46-
Problem: Search Maximum
const int size = 50;
int numbers[size];
int max;
for (int i = 0; i < size; i++)
{
cout<< "Enter number: ";
cin>> numbers[i];
}
max = numbers[0];
for (int i = 1; i < size; i++)
if (numbers[i] > max)
max = numbers[i];
cout<< "Maximum number: "<< max << endl;
-47-
const int size = 5;
int scores[size];
Problem
int max; Search Max
Index
for (int i = 0; i < size; i++)
cin>> scores[i];

max = scores[0];
for (int i = 1; i < size; i++)
if (scores[i] > max)
max = scores[i];

cout<< "Maximum score: "<< max << endl;


cout<<"Achieved by Students:\n";
for (int i = 0; i < size; i++)
if (scores[i] == max) Student 1 score is stored in index 0
cout<< i+1 << endl;
-48-
Assignment 1 (Home Project)

 A factory has multiple production lines. Each production line


has a maximum price for its products.
 Each product belongs to a specific production line, has a base
price, taxes and net price.
 Write a C++ program that reads data of 3 products then
computes the net price and determines if the computed net
price is accepted compared with the maximum price of the
corresponding production line.
 N.B.
taxes
 net price = base price + base price x
100
 net price of each product should not exceed the maximum price of the
corresponding production line.
-49-
Sample Run

-50-
To-Do List:
1. Sheet 1
2. Home Assignment 1
3. Clean code presentation (Self-Study)

You might also like