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

Lec19 21 Arrays

- An array is a data structure that stores a collection of related data items of the same type in contiguous memory locations. - In C++, arrays can have one or more dimensions. One-dimensional arrays are commonly used to represent strings by storing characters. - Elements within an array are accessed using an index, with the first element having an index of 0. Multi-dimensional arrays allow accessing elements using multiple indices, one for each dimension of the array.

Uploaded by

Asad Haneef
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Lec19 21 Arrays

- An array is a data structure that stores a collection of related data items of the same type in contiguous memory locations. - In C++, arrays can have one or more dimensions. One-dimensional arrays are commonly used to represent strings by storing characters. - Elements within an array are accessed using an index, with the first element having an index of 0. Multi-dimensional arrays allow accessing elements using multiple indices, one for each dimension of the array.

Uploaded by

Asad Haneef
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 91

Ternary/Conditional Operator (?

:)
Syntax
(condition) ? (if_true) : (if_false)

Example
int largest = ((a > b) ? a : b);

Ternary/Conditional Operator (?:)


int x=0; (x==0) ? (x=20) : (x=30); cout << x << endl;

Ternary Operator Vs If Statement


The ternary operator is an expression whereas the if structure is a statement.
A ternary operator expression's result can be assigned to a variable, the results of an if statement cannot.

Ternary Operator Vs If Statement


The advantage that the if statement has is that you can have multiple clauses, where as with the ternary operator you can have only two.

Arrays

Arrays offer a convenient means of grouping together several related variables

List of marks List of names

Declaring an array
type array_name[size]; allocates memory for size variables index of first element is 0 index of last element is size-1 size must be a constant

Declaring an array- Example


Example: int list[10];

allocates memory for 10 integer variables index of first element is 0 index of last element is 9 C++ does not perform any bounds checking on arrays
list[9]

list[1] list[0]

Arrays
One- dimensional arrays type var_name[size]; int sample[10]; double d[30]; char ch[100];

Initializing Arrays
Arrays can be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; int num[10] ={0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Initializing Arrays
What is wrong with the following? int num=10; int iarray[num];

int size; cin>>size; int myArray[size];


double dArray[5]={3.2, 4.5, 6.7, 324.0, 45.8, 23.1, 34.9};

C++ does not bound check arrays


int intArray[5]={1, 2, 3, 4, 5};
for (int i=0; i<6; i++) { cout << intArray[i]<<endl; }

Lecture 20

Assigning values to an array


Example

int list[10]; int count, i; cin >> count; for(int i=0; i<count; i++) cin >> list[i];
for loops are often used to assign values to an array

Assigning values to an array


Example

int list[10]; int count, i; cin >> count; for(int i=0; i<count; i++) cin >> list[i];
What if count >9?

Assigning values to an array


int main() {
// this reserves 10 integer elements

int sample[10]; int t; // load the array for(t=0; t<10; ++t) sample[t]=t; // display the array for(t=0; t<10; ++t) cout << sample[t] << return 0; } //output ?

Arrays
Output is: 0123456789

Summarize Arrays
An array is an indexed data structure An element of an array is accessed using the array name and an index An array stores a collection of variables All variables stored in an array are of the same data type An individual variable within an array is called an element of the array

Summarize Arrays
In C++ all arrays are stored in contiguous memory locations An index describes the position of an element within an array. In C++ all arrays have zero as the index of their first element. The name of the array is the address of the first element. The index is the offset

Arrays
Total size of an array in bytes? Total bytes = (number of bytes in type) x (number of elements) e.g. int sample[10];

sizeof operator

Arrays
int a[10]; cout<<sizeof(a)<<endl; cout<<sizeof(a[0])<<endl; cout<<sizeof(int)<<endl; double d[10]; cout<<sizeof(d)<<endl; cout<<sizeof(d[0])<<endl; cout<<sizeof(double)<<endl;

Arrays
40 4 4 80 8 8

Arrays Review
Arrays used for grouping of related variables.

int a1; int a[5]; int a2; int a3; int a4; int a5; Individual elements of array accessed by indices. Easier to use in loops.

Arrays Review
int a[5] = {10, 20, 30, 40, 50}; a[0] is 10 a[1] is 20 a[2] is 30 a[3] is 40 a[4] is 50 No boundary checking of arrays because of efficiency reasons. Error checking can slow down the program execution.

A variable is a named memory location that may be assigned a value.

0x0012F588

50

a[4]

0x0012F584 0x0012F580 0x0012F57C 0x0012F578

40 30 20 10

a[3] a[2] a[1] a[0]

What is wrong here?

const int x;

Arrays
int myArray[3]; myArray[0]=0; myArray[1]=1; myArray[2]=2; OR int myArray[3] = {0,1,2}; OR int myArray[] = {0,1,2}; int myArray[3]={}; //intializes all elements to 0
int myArray[]={};//Error:cant allocate an array of constant size 0

Arrays
int main() { int i, min_value, max_value; int list[10]; for(i=0; i<10; i++){ list[i] = rand(); cout<<list[i]<<" "; }

Arrays
// find minimum value min_value = list[0]; for(i=0; i<10; i++) { if(min_value>list[i]){ min_value = list[i]; } }
cout << "minimum value: " << min_value << \n;

Arrays
// find maximum value max_value = list[0]; for(i=0; i<10; i++){ if(max_value<list[i]){ max_value = list[i]; } } cout << "maximum value: " << max_value << '\n'; return 0;

Arrays
int a[10], b[10]; // ... a = b; // error illegal. /* The name of the array is the address of the first element. The index is the offset So how do we make the contents of one array same as the other?*/

Arrays
int a[5]={1,2,3,4,5}, b[5]; for (int i=0; i<5; i++) { b[i]=a[i]; }

Arrays
Finding size of an array
int a[]= {1,2,4,5,7,9,12}; cout << "size: " << sizeof(a)/sizeof(a[0]) << endl;

Lecture 21

Strings
One dimensional arrays are used to create character strings In C++, a string is defined as a character array that is terminated by a null A null is specified using \0 and is zero Because of the null terminator, it is necessary to declare a character array to be one character longer than the largest string it will hold.

Character Arrays
char word[6] = fruit; //word has size 6

char list[6] = {f,r,u,i,t, \0}; //list of characters, not a string Not necessary to add null terminator at end of string constants.

Character Arrays
char word[] = fruit; //word has size 6

What is wrong with the following?

char name[5]="class"; int MyArray[];

'a' and "a" are different

Null String

""
Only contains null terminator.

Reading strings from keyboard


The easiest way to read a string entered from the keyboard is to make a character array
int main() { char str[80]; cout << "Enter a string: "; cin >> str; // read string from keyboard cout << "Here is your string: ";
cout << str<<"\n"; return 0;

Reading strings from keyboard


There is a problem with previous program, if the string has whitespace characters
// Using gets() to read a string from the keyboard. #include <stdio.h>

int main() { char str[80]; cout << "Enter a string: "; cout<<flush; gets(str); // read a string from the keyboard //NOTE: gets takes array_name as parameter cout << "Here is your string: "; cout << str<<\n; return 0; }

When you send output to cout, it does not necessarily get printed immediately. Rather, it may wait in a buffer until some event, e.g. buffer full enough, reading from input etc. Forcing all buffered output to actually be printed is known as "flushing" the stream. A flush can be forced by inserting flush into the stream, or inserting endl.

cout << flush; cout << endl;

HomeWork (hard copy due in next class)


Get string input (of length no greater than 10) from keyboard and store in a char array using gets function provided by C++ stdio.h library Print the inverted string

HomeWork (hard copy due in next class)


Example: Input string: my str Output: rts ym

Sorting an array
Lots of applications require sorting Algorithm for sorting

Sorting an array double dArray[10]= {34, 5.6, 0.9, 345.7, 54.1, 23.5, 2.5, 6.78, 12.4, 13.9};

Sorting an array
int main(void){ const int size=10; int i, j; double dArray[size]={34, 5.6, 0.9, 345.7, 54.1, 23.5, 2.5, 6.78, 12.4, 13.9}; double temp; for (i=0; i<size; i++){ for (j=i+1; j<size; j++){ if (dArray[j]<dArray[i]){ temp=dArray[j]; dArray[j]=dArray[i]; dArray[i]=temp;
} } } //in-place sorting

return 0; }

Self Test: Sorting an array


Modify the previous program so that it does not do in-place sorting, but instead stores the sorted list in another array.

Lecture 22

Self Test: Sorting an array


// Using the bubble sort to order an array. int main() { int nums[10]; int a, b, t; int size; size = 10; // number of elements to sort // give the array some random initial values for(t=0; t<size; t++) nums[t] = rand();

Self Test: Sorting an array (Simulate)


// This is the bubble sort. for(a=1; a<size; a++) for(b=size-1; b>=a; b--) { if(nums[b-1] > nums[b]) { // if out of order // exchange elements t = nums[b-1]; nums[b-1] = nums[b]; nums[b] = t; } } // This is the end of the bubble sort.

Bubble Sort Simulation

Two Dimensional Arrays


C++ supports multi-dimensional arrays

type array_name[row_size][column_size] int matrix[3][4];


row[0] row[1] row[2]

Two dimensional arrays


int array[2][3] = {{1,2,3}, {4,5,6}};
int E[][2]={ 1,2, 3,4 };

Accessing Array Elements


int matrix[3][4];

matrix has 12 integer elements matrix[0][0] element in first row, first column matrix[2][3] element in last row, last column

Two Dimensional Arrays


int jimmy[3][5];

Two Dimensional Arrays int main() { const int rows=3, cols=4; int i, j, num[rows][cols]; for(i=0; i<rows; ++i) { for(j=0; j<cols; ++j) { num[i][j]= (i*cols)+j+1; cout << num[i][j]<<"\t"; } cout << "\n"; } return 0; } // output?

Output: 1 2 5 6 9 10

3 7 11

4 8 12

int main() What happens if I change [3][4] to [2][6]? { const int rows=2, cols=6; int i, j, num[rows][cols]; for(i=0; i<rows; ++i) { for(j=0; j<cols; ++j) { num[i][j]= (i*cols)+j+1; cout << num[i][j]<<"\t"; } cout << "\n"; } return 0; } // output?

Two Dimensional Arrays

Output: 1 2 7 8

3 9

4 10

5 11

6 12

Self Test: Arrays


Print the transpose of a 2-D array.

Self Test: Arrays


Print the transpose of a 2-D array for(int i=0; i<cols; ++i) { for(int j=0; j<rows; ++j) { cout << num[j][i] << "\t"; } cout << "\n"; }

Practice Exercise!
Write down the code to multiply two matrices of sizes NxM and MxQ respectively.

Arrays
int a[10] = {1,2,3,4,0,3,4,6,7,8}; int x=3; y=1; cout<< a[x+2*y] <<\n; cout<<Answer= <<a[a[a[4]]]<<\n; Output?

Arrays
int a[10] = {1,2,3,4,0,3,4,6,7,8}; int x=3; y=1; cout<< a[x+2*y] <<\n; cout<<Answer= <<a[a[a[4]]]<<\n; Output: 3 Answer= 2

The name of the array is the address of the first element. It is a constant.
int a[5]={13, 5, 6, 34, 6}; cout<<a[1]<<endl; cout<<a[3]<<endl; cout<<a[4]<<endl; cout<<a<<endl;

The name of the array is the address of the first element. It is a constant.
5 34 6 0x0012FEC4

char str[]="fruit"; cout<<str[1]<<endl; cout<<str[3]<<endl; cout<<str[4]<<endl; cout<<str<<endl;

r i t fruit

int twoD[4][2]={ 1, 10, 2, 13, 3, 34, 4, 15 };


Picture of array

twoD[1][1] is twoD[2][0] is

int twoD[4][2]={ 1, 10, 2, 13, 3, 34, 4, 15 };


Picture of array

twoD[1][1] is 13 twoD[2][0] is 3

Arrays of strings
char strings[6][80]={ "one", "two", {'t','h','r','e','e',\0}, "four", "five", "" }; Picture of array

cout<<strings[1][1]<<endl; cout<<strings[2][0]<<endl; cout<<strings[1]<<endl; cout<<strings[2]<<endl;

Arrays of strings
char strings[6][80]={ "one", "two", {'t','h','r','e','e', '\0'}, "four", "five", "" }; Picture of array

cout<<strings[1][1]<<endl; // w cout<<strings[2][0]<<endl; // t cout<<strings[1]<<endl; //two cout<<strings[2]<<endl; //three

Arrays of strings
char strings[6][80]={ "one", "two", {'t','h','r','e','e,\0}, "four", "five", "" }; int i=0; while(strings[i][0]){ cout<<strings[i]<<endl; i++; }

char str[]="This is CS"; int i=0; while(str[i]){ cout<<str[i]<<endl; i++; }

T h i s i s C S

What if I insert a zero? char str[]="This is 0CS"; int i=0; while(str[i]){ cout<<str[i]<<endl; i++; }

char str[80]; do{ gets(str); cout<<str<<endl; }while(str[0]);

String Library Functions


strcpy() strcat() strlen() strcmp()

#include <string>
strcpy(to, from) int main() { char str[80]; strcpy(str, "hello"); cout << str; return 0; }

String Library Functions


strcpy() strcat() strlen() strcmp()

#include <string>
strcpy(to, from) int main() { char str[80]; strcpy(str, "hello"); cout << str; return 0; }
Output is: hello

String Library Functions (strcat)


int main() { char s1[20], s2[10]; strcpy(s1, "hello"); strcpy(s2, " there"); strcat(s1, s2); cout << s1<< "\n"; return 0; } //output?

Output is: hello there

String Library Functions (strcmp)


strcmp(s1,s2) compares two strings and returns 0
if they are equal. If s1 is greater than s2 (dictionary order) then a positive number is returned; if it is less than s2 then a negative number is returned.

cout<<strcmp("abc", "def")<<endl;
Prints -1

String Library Functions (strlen) strlen(s) returns the length of s (not counting null terminator) int main() { char str[80]; cout << "Enter a string\n"; gets(str); cout << "Length is: " << strlen(str)<<"\n"; return 0; } //what is the output if we enter: this is cs

What is wrong here?


char words[3]; strcpy (words, Now, here is a long string.);

What is wrong here?


char words[3]; strcpy (words, Now, here is a long string.); Will continue to fill whatever memory follows last indexed variable of words, even though this memory may be used for something else.

What is wrong with following?


char str1[80]=i am a string; char str2[80]=i am a string; if (str1==str2) cout<<equal; else cout<<not equal;

What is wrong with following?


char str1[80]=i am a string; char str2[80]=i am a string; if (str1==str2) cout<<equal; else cout<<not equal; // Use strcmp(str1, str2)

What is wrong with following?


char str1[80]="cs"; char str2[80]; str2=str1;

What is wrong with following?


char str1[80]="cs"; char str2[80]; str2=str1; //Error

Use strcpy(str2, str1);

You might also like