Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-161 Computer Programming Lecture 15 & 16: Arrays II

Similar presentations


Presentation on theme: "CS-161 Computer Programming Lecture 15 & 16: Arrays II"— Presentation transcript:

1 CS-161 Computer Programming Lecture 15 & 16: Arrays II
Fall 2014 (Sections A & B) Saqib Rasheed

2 Reserve Arrays

3 Printing a Sequence in Order
This program reads five numbers and then prints them in reverse order: Out Put Enter 5 numbers: 20 30 40 50 In reverse order: 10

4 #include<iostream.h>
void main() { const int SIZE=5; int i,a[SIZE]; cout << "Enter " << SIZE << " numbers:\n"; for ( i=0; i<SIZE; i++) cin >> a[i]; cout << "In reverse order: \n"; for ( i=SIZE-1; i>=0; i--) cout << "\t" << a[i]<<endl; }

5 Copy Arrays

6 Copying Arrays Data types should be identical Size should be same
int a [ 10 ] ; int b [ 10 ] ;

7 Copying Arrays To copy from array “ a ” to array “ b ” :
b [ 0 ] = a [ 0 ] ; b [ 1 ] = a [ 1 ] ; b [ 2 ] = a [ 2 ] ; b [ 3 ] = a [ 3 ] ; … … … b [ 10 ] = a [ 10 ] ;

8 Copying Arrays for ( i =0 ; i < 10 ; i ++ ) b [ i ] = a [ i ] ;

9 Adding Arrays

10 Adding 1 D a[0]=10 + b[0]=1 = add[0]=11 a[1]=11 + b[1]=2 = add[1]=13
Array Array 2 = Array 3 a[0]=10 + b[0]=1 = add[0]=11 a[1]=11 + b[1]=2 = add[1]=13 a[2]=12 + b[2]=3 = add[2]=15 a[3]=13 + b[3]=4 = add[3]=17 a[4]=14 + b[4]=5 = add[4]=19

11 Adding 1 D(code) #include<iostream.h> void main () {
float ar1[5], ar2[5],add[5]; int i; cout<<"\nEnter the value for array 1\n"; for(i=0; i<=4; i++) cout<<"Array 1 Index ["<<i<<"]="; cin>>ar1[i]; }

12 Adding 1 D(code) cout<<"\nEnter the value for array 2\n";
for(i=0; i<=4; i++) { cout<<"Array 2 Index ["<<i<<"]="; cin>>ar2[i]; } cout<<"\n\tArray 1 + Array 2 = Array 3\n"; add[i] = ar1[i] + ar2[i]; cout<<"\n\tSum at Index ["<<i<<"]="<<add[i]; cout<<endl;}

13 Searching Arrays

14 Searching Arrays: Linear Search
Search array for a key value 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

15 Example (Array Search)
#include<iostream> using namespace std; void main () { const int size=10; int a[size]={ 5,6,1,8,3,7,2,10,9,4}; for(int k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl; int searchKey; cout << "Enter integer search key: "; cin >> searchKey;

16 for( k=0; k<size; k++)
if (a[k]==searchKey) cout<<"The element to be searched is found at index a["<<k<<"]"; cout<<endl; }

17 Passing Arrays to Functions

18 Passing Arrays to Functions
Specify name without brackets To pass array myArray to myFunction int myArray[ 24 ]; myFunction( myArray, 24 ); Array size usually passed, but not required Useful to iterate over all elements

19 Passing Arrays to Functions
Arrays passed-by-reference Functions can modify original array data Value of name of array is address of first element Function knows where the array is stored Can change original memory locations Individual array elements passed-by-value Like regular variables square( myArray[3] );

20 Passing Arrays to Functions
Functions taking arrays Function prototype void modifyArray( int b[], int arraySize ); void modifyArray( int [], int ); Names optional in prototype Both take an integer array and a single integer No need for array size between brackets Ignored by compiler If declare array parameter as const Cannot be modified (compiler error) void doNotModify( const int [] );

21 Example (Passing Array to Functions)
void function1(int [], int); void function2(int); void main () { const int size=5; int array[]={1, 2,3 ,4,5}; cout<<"Array elements before function call:"; for (int i=0; i<5;i++) cout<<array[i]<<" "; cout<<endl;

22 function1(array, 5); cout<<endl; cout<<"Array elements after function call\n"; for (i=0; i<size;i++) cout<<array[i]<<" "; cout<<"passing array element array[2] to the function\n"; cout<<"Before:"<<array[2]<<endl; function2(array[2]); cout<<"After:"<<array[2]<<endl; }

23 //function definitions
void function1(int a[],int size) { cout<<"Array elements in function call\n"; for (int i=0; i<size; i++) cout<<(a[i]*=2)<<" "; } void function2( int x) { cout<<"In Function:"; cout<<x*2<<endl;

24 Array Sorting

25 Sorting Arrays Sorting data Bubble sort
Important computing application Virtually every organization must sort some data Bubble sort Several passes through the array (assume: elements are to be sorted in increasing order) Successive pairs of elements are compared If increasing order (or identical), no change If decreasing order, elements exchanged Repeat these steps for every element

26 Sorting Arrays Example:
Go left to right, and exchange elements as necessary One pass for each element Original: Pass 1: (elements exchanged) Pass 2: Pass 3: (no changes needed) Pass 4: Pass 5:

27 Sorting Arrays Swapping variables What happened? Solution
int x = 3, y = 4; y = x; x = y; What happened? Both x and y are 3! Need a temporary variable Solution int x = 3, y = 4, temp = 0; temp = x; // temp gets 3 x = y; // x gets 4 y = temp; // y gets 3

28 Example (Array Sorting)
#include<iostream> using namespace std; void main () { const int size=10; int a[size]={ 5,6,1,8,3,7,2,10,9,4}; for(int k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl;

29 int temp; //sorting process for ( int pass = 0; pass < size - 1; pass++ ) for ( int j = 0; j < size - 1; j++ ) // loop to control number of comparisons per pass if ( a[ j ] > a[ j + 1 ] ) { temp = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = temp; } cout<<"Sorted Array\n"; for( k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl;

30 Character Arrays

31 Character Arrays 2 kinds of strings C-Strings Objects of String class

32 Contd… Strings Arrays of characters All strings end with null ('\0')
Examples char string1[] = "hello"; Null character implicitly added string1 has 6 elements char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0’ }; Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l'

33 Contd… Input from keyboard Printing strings Puts user input in string
char string2[ 10 ]; cin >> string2; Puts user input in string Stops at first whitespace character Adds null character If too much text entered, data written beyond array Printing strings cout << string2 << endl; Does not work for other array types Characters printed until null found

34 Example (C-String Variable)
#include<iostream> using namespace std; void main () { char a[20]; cout<<"Enter String\n"; cin>>a; cout<<"you entered "<<a<<endl; }

35 Example (String Constants)
#include<iostream> using namespace std; void main () { char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout << question; cin >> yourname; cout << greeting << yourname << "!"<<endl; }

36 Example (Reading Embedded Blanks)
#include<iostream> using namespace std; void main () { char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout << question; cin.get(yourname,80); cout << greeting << yourname << "!"<<endl; }

37 Reading Multiple Lines
#include <iostream> using namespace std; const int MAX = 2000; //max characters in string char str[MAX]; //string variable str int main() { cout << “\nEnter a string:\n”; cin.get(str, MAX, ‘$’); //terminate with $ cout << “You entered:\n” << str << endl; return 0; }

38 The string type Like cout, the string type is not part of the C++ language itself, it is defined in a header file string. To use it, we have to include the header file: #include <string> Note that we have to use <string>, not <string.h> A variable of type string can contain a string like "Hello World". The length of the string can change during the execution of the program.

39 The string type No need to specify array size (responsibility of memory management) A string variable is declared as follows: string s1; Declare a new string We can also initialize it with a value as follows: string hello = "Hello World"; We can output the string as usual: cout << hello << endl; // prints "Hello World"

40 Two strings can be concatenated
string aa, newstr; aa = 'A'; newstr = aa + " " + hello; // newstr == "A Hello World" newstr += "!!"; // newstr == "A hello World!!";

41 Example #include<iostream> #include<string> using namespace std; void main () { string question = "Please, enter your first name: "; string greeting ("Hello, "); string yourname; cout << question; getline(cin, yourname); cout<<greeting+yourname<<endl; }

42 strlen, strcpy() & strcmp()
Strlen (array); tells the length of the array Strcpy(destination, source); Copies the source values to the destination Strcmp(str1, str2); compares two strings str1 & str2 and gives the integer value. 0 indicates the matching strings Otherwise not same

43 String Operations Strlen Strcpy Strncpy Strcmp Strcat

44 strlen Determine string length strlen(string);
Returns number of characters in string Terminating null character is not included in length

45 strlen #include <iostream.h> #include <string.h>
void main (void) { char x [40], char y [40], z[40]; strcpy (x, "Pakistan"); strcpy (y, "USA"); strcpy (z, "Italy"); cout << "X length is =" << strlen (x) << endl; cout << "Y length is =" << strlen (y) << endl; cout << "z length is =" << strlen (z) << endl; }

46 Output

47 strcpy strcpy is used to copy one string into an other
strcpy(string1,string2);

48 strcpy #include <iostream.h> #include <string.h>
void main (void) { char x [ ] = “Pakistan is a great country”; char y [28]; strcpy (y, x ); cout << “X is = “ << x << “\n”; cout << “Y is = “ << y << “\n”; }

49 Output

50 strcmp strcmp is used to compare two strings strcmp(string1,string2);

51 strcmp #include <iostream.h> #include <string.h>
void main (void) { int check; char x [ ] = "Pakistan is a great country"; char y [ ] = "Pakistan is a great country"; char z [ ] = "Pakistan is a country"; char f [ ] = "pakistan is a great country"; check=strcmp (y, x ); //both strings are same cout<<check; //check = 0 check=strcmp(y,z); //both strings are different, length of 1st > 2nd cout<<check; //check = 1 check=strcmp(z,y); //both strings are different, length of 2nd > 1st cout<<check; //check = -1 check=strcmp(f,y); //first characters of both strings are different }

52 Output

53 strcat appends a copy of the source string to the destination string
/* strcat example */ #include <stdio.h> #include <string.h> int main () { char str[80]; strcpy (str,"these "); strcat (str,"strings "); strcat (str,"are "); strcat (str,"concatenated."); puts (str); return 0; }

54 Output


Download ppt "CS-161 Computer Programming Lecture 15 & 16: Arrays II"

Similar presentations


Ads by Google