Uploaded by trueyemagdy15092005

C++ One-Dimensional Arrays: Structured Programming Lecture

advertisement
Structured Programming
Lecture 1
One Dimensional Arrays
Course Logistics
• Instructors
– Dr. Maryam Nabil (Scientific Computing Department)
– Dr. Salsabil Amin (Basic Sciences Department)
• Contact: salsabil_amin@cis.asu.edu.eg
• Office: 3rd floor, next to Tolba Lecture hall
– Dr. Naglaa Fathy (Information Systems Department)
• Contact: naglaa_fathy@cis.asu.edu.eg
• 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
Midterm
Practical
Project
Quiz 1 (in lab)
Quiz 2 (online)
Lecture Bonus
50
15
10
15
5
5
+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)
c[0]
-45
c[1]
6
c[2]
0
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
How
many
elements
in 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 ??
5th Element??
5th Array
element
at index 4
float myList[10];
myList[0]
5.6
myList[1]
4.5
myList[2]
3.3
myList[3]
13.2
myList[4]
65.3
myList[5]
34.33
myList[6]
34.0
myList[7]
45.45
myList[8]
99.993
myList[9]
111.23
5th
Element
value
-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?
double grades[10];
Array size
= number
of elements
(Const)
cout << grades[0];
Position/
index of
array
element
(can be
variable)
grades[9] = 97.5;
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;
s[i]
i
0 2+0=2
for (int i = 0; i < arraySize ; i++)
1
2+2=4
cout<< s[i] << ", ";
2
...
9
2+4=6
...
2+18=20
-31-
Exercise
C++ Code
Correct?
int arraySize = 5;
float numbers[arraySize];
for ( int i = 0; i < arraySize; i++ )
cin >> numbers[i];
Wrong
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++ )
cin >> grade[i];
Wrong
-32-
Exercise
C++ Code
Correct?
int numbers[2] = {11, 33, 44};
Wrong
int numbers[1];
numbers = 34;
Wrong
float numbers[0];
Wrong
float price[]= {33.5, 25, 56, 77.25};
Correct
-33-
*
Exercise: Output?
Random numbers from 0 to 99
num
num%3
6
0
7
1
8
2
9
0
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
for (int i = 1; i < 5; i++)
i
values[i] = i + values[i-1];
1
values[0] = values[1] + values[4];
2
init
1st,
i=1
2nd,
i=2
3rd,
i=3
4th,
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
3
4
values[i]
1+0=1
2+1=3
3+3=6
4+6=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;
cout<< "Average: "<< average << endl;
Problem?
-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;
for (int i = 0; i < size; i++)
{
cout<< "Enter number: ";
cin>> numbers[i];
}
*
Does it work
for negative
numbers?
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];
int max;
for (int i = 0; i < size; i++)
cin>> scores[i];
Problem
Search Max
Index
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++)
Student 1 score is stored in index 0
if (scores[i] == max)
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.
 net price = base price + base price x
taxes
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)
Download