• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Computer Programming- Lecture 8
 

Computer Programming- Lecture 8

on

  • 4,133 views

Arrays

Arrays

Statistics

Views

Total Views
4,133
Views on SlideShare
278
Embed Views
3,855

Actions

Likes
0
Downloads
24
Comments
0

2 Embeds 3,855

http://drshohel.net 3851
http://edit.optimizely.com 4

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Computer Programming- Lecture 8 Computer Programming- Lecture 8 Presentation Transcript

    • Lecture 8 ArraysTCP1231 Computer Programming I 1
    • Objectives • To Learn about arrays • Explore how to declare and manipulate data into arrays • Understand the meaning of “array index out of bounds” • Become familiar with the restrictions on array processing TCP1231 Computer Programming I 2
    • Introduction to Arrays• Given this scenario … – Write a program that reads five numbers, and performs some manipulations on these numbers, such as find their sum, and print the numbers in reverse order – We could use five individual variables of type int, but five variables are hard to keep track of – We could make program more readable by giving the variables related names such as item1, item2, item3, and so forth, but this solution becomes absurd if the number of items is very large TCP1231 Computer Programming I 3
    • Program: Read five numbers, find their sum, and printthe numbers in reverse order#include <iostream>using namespace std;int main(){ int item0, item1, item2, item3, item4; int sum; cout<<"Enter five integers: "; cin>>item0>>item1>>item2>>item3>>item4 <<endl; sum = item0 + item1 + item2 + item3 + item4; cout<<"The sum of the numbers = "<<sum<<endl; cout<<"The numbers in reverse order are: "; cout<<item4<<" "<<item3<<" "<<item2<<" " << item1<<" "<<item0<<endl; return 0;} TCP1231 Computer Programming I 4
    • ArraysArrays: are a series of elements (variables) of the same type placed consecutively inmemory that can be individually referenced by adding an index to a unique name.Explanations: This means that, for example, we can store 5 values of type int withouthaving to declare 5 different variables each with a different identifier. Instead, using anarray we can store 5 different values of the same type, int for example, with a uniqueidentifier.For example, an array to contain 5 integer values of type int called item could berepresented this way: int item[5]; 0 1 2 3 4 item intwhere each blank panel represents an element of the array, that in this case areinteger values of type int. These are numbered from 0 to 4 since in arrays thefirst index is always 0, independently of its length . TCP1231 Computer Programming I 5
    • ArraysLike any other variable, an array must be declared before it is used.A typical declaration for an array in C++ is: type name [elements];where type is a valid object type (int, float...), name is a validvariable identifier and the elements field, that is enclosed withinbrackets [], specifies how many of these elements the arraycontains. Therefore, to declare item as shown above it is as simpleas the following sentence: int item[5];NOTE: The elements field within brackets [] when declaring anarray must be a constant value, since arrays are blocks of staticmemory of a given size and the compiler must be able to determineexactly how much memory it must assign to the array before anyinstruction is considered. TCP1231 Computer Programming I 6
    • Initializing arraysWhen declaring an array of local scope (within a function), if wedo not specify otherwise, it will not be initialized, so its content isundetermined until we store some values in it. If we declare aglobal array (outside any function) its content will be initializedwith all its elements filled with zeros. Thus, if in the global scopewe declare: int item[5];every element of item will be set initially to 0: 0 1 2 3 4 item 0 0 0 0 0 TCP1231 Computer Programming I 7
    • Initializing arraysWhen we declare an Array, we have the possibility to assign initialvalues to each one of its elements using curly brackets { }. Forexample: int item [5] = { 16, 2, 77, 40, 12071 };This declaration would have created an array like the following one: 0 1 2 3 4 item 16 2 77 44 12071The number of elements in the array that we initialized within curly brackets { }must match the length in elements that we declared for the array enclosed withinsquare brackets [ ]. int item [] = { 16, 2, 77, 40, 12071 }; TCP1231 Computer Programming I 8
    • Program 1: Read five numbers, find their sum, and printthe numbers in reverse orderint main(){ int item[5]; //declare an array item of five components int sum=0; cout<<"Enter five numbers."<<endl; cin>>item[0] >> item[1] >> item[2] >> item[3] >> item[4] >> item[5] ; sum = sum + item[0] + item[1] + item[2] + item[3] + item[4] + item[5]; cout<<"The sum of the numbers is: "<<sum<<endl; cout<<"The numbers in reverse order are: "; cout<<item[4]<<“ "<<item[3]<<" "<<item[2]<<" " << item[1]<<" "<<item[0]<<endl; return 0;} TCP1231 Computer Programming I 9
    • Program 2: Read five numbers, find their sum, andprint the numbers in reverse orderint main(){ int item[5]; //declare an array item of five components int sum=0, int counter; cout<<"Enter five numbers."<<endl; for(counter = 0; counter < 5; counter++) { cin>>item[counter]; sum = sum + item[counter]; } cout<<"The sum of the numbers is: "<<sum<<endl; cout<<"The numbers in reverse order are: "; for(counter = 4; counter >= 0; counter--) cout<<item[counter]<<" "; return 0;} TCP1231 Computer Programming I 10
    • Program 3: Read five numbers, find and print thesmallest number among themint main (){ double a[10]; double sml; for (int i=0; i<=4; i++) cin >> a[i]; sml=a[0]; for (int i=1; i<=4; i++) { if (sml > a[i]) sml=a[i]; } cout << "the smallest number is: " << sml; getch(); return 0;} TCP1231 Computer Programming I 11
    • Access the values of an Array• The values of an array can be access using following format: name[index]• From previous example, item has 5 elements and each of those elements is of type int To store the value of 33 in the second element of item: item[1] = 33; To pass the value of the second element of item to the variable temporary: temporary = item[1];• Notice that the second element of item is specified item[1], since first is item[0], therefore, the second is item[1]. By this same reason, its last element is item[4]. If we write item[5], we will be acceding to the sixth element of item and therefore exceeding the size of the array TCP1231 Computer Programming I 12
    • Access the values of an Array• In C++ it is perfectly valid to exceed the valid range of indices for an Array, which can create problems since they do not cause compilation errors but they can cause unexpected results or serious errors during execution. The reason why this is allowed will be seen farther ahead when we begin to use pointers• At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays – To set the size of arrays when declaring them int item[5]; // declaration of a new Array (begins with a type name) – To specify indices for a concrete array element when referring to it item[1] = 33; // access to an element of the Array TCP1231 Computer Programming I 13
    • Sort Algorithm (Selection)1. Search for the smallest value in the array – the smallest value is the value in a[3]2. Place the smallest value in a[0], and place the value that was in a[0] in a[3], the location where the smallest was found3. Starting at a[1], find the smallest remaining value, swap it with the value currently in a[1]4. Starting at a[2], continue the process until the array is sorted 14 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
    • int main () for (int k=0; k<=3; k++){ { double a[5]; sml=a[k]; double sml, temp; Psml=k; int Psml; //index of small for (int i=k; i<=4; i++) if (sml > a[i]) for (int i=0; i<=4; i++) { { sml=a[i]; cout << “enter a[“<< i <<“] ” ; Psml=i; cin >> a[i]; } } temp=a[Psml]; cout << "nthe current array "; a[Psml]=a[k]; for (int i=0; i<=4; i++) a[k]=temp; cout << a[i] << t; } cout << "nthe sorted array: "; for (int i=0; i<=4; i++) cout << a[i] << t; return 0; } TCP1231 Computer Programming I 15
    • Sort Algorithm (Bubble)#include <iostream> for (i=0; i<=4; i++)using namespace std; for (j=0; j<=3; j++) if (a[j]>a[j+1])int main () {{ temp=a[j]; int a[5]; a[j]=a[j+1]; int i,j, temp; a[j+1]=temp; } for (int i=0; i<=4; i++) cout << "nthe sorted array: "; { for (i=0; i<=4; i++) cout << "enter a["<< i <<"] "; cout << a[i] << t; cin >> a[i]; } return 0; } cout << "nthe current array "; for (int i=0; i<=4; i++) cout << a[i] << t; 16 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
    • Sequential Search Algorithm• Sequential search is to determine the index i position of an object ‘X’ in an array A int search (const int a[], int target 8 number_used, int target) { [0] [1] [2] [3] [4] [5] [6] [7] int index = 0; bool found = false; a 2 7 3 8 4 12 9 5 while ((!found) && (index < number_used)) if (target == a[index]) Found “8” in position 4 found = true; else index++; if (found) return index; else return -1; } 17 http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/appldsal.html TCP1231 Computer Programming I
    • THE ENDTCP1231 Computer Programming I 18