Arrays: Aryaf Aladwan

Download as pdf or txt
Download as pdf or txt
You are on page 1of 115

Chapter 3

Arrays

1
Aryaf Aladwan
Arrays

• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
– Specify array name and position number (index)
– Syntax : arrayname[ position number ]
– First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1

2
Aryaf Aladwan
3
Aryaf Aladwan
4
Aryaf Aladwan
5
Aryaf Aladwan
6
Aryaf Aladwan
Arrays

• Array elements like other variables


– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
• Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]

7
Aryaf Aladwan
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

8
Aryaf Aladwan
9
Aryaf Aladwan
10
Aryaf Aladwan
11
Aryaf Aladwan
12
Aryaf Aladwan
13
Aryaf Aladwan
14
Aryaf Aladwan
15
Aryaf Aladwan
16
Aryaf Aladwan
17
Aryaf Aladwan
Declaring Arrays

• When declaring arrays, specify


– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
char x4[5]; // array of 5 characters
int n = 10;
int x[n]; Error ➔ const int n = 10;

• Declaring multiple arrays of same type


– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
18
Aryaf Aladwan
19
Aryaf Aladwan
20
Aryaf Aladwan
21
Aryaf Aladwan
Arrays Initialization

1) Group Initialization

2) Element wise Initialization

3) Initialization using loops

22
Aryaf Aladwan
Group Initialization

int a[9] = { 1,3,5,7,9,11,12,13,9};


float b[4] = { 0.1,0.3,0.7,1.8};
char c[4] = { ′H ′, ′ e ′, ′ L ′, ′ p ′};
int numbers[] = { 12,7,9,5,12};
int arry[5]= {1,8,6,7,5,9}; error
int num[4]= { 9,5,3}; num[3] = 0
char std[4]={′f ′, ′s ′, ′w ′}; std[3] = ′ \0 ′

23
Aryaf Aladwan
24
Aryaf Aladwan
25
Aryaf Aladwan
26
Aryaf Aladwan
27
Aryaf Aladwan
Element wise Initialization
#include<iostream.h>
void main()
{
int x[4];
x[0]=3;
x[1]=1;
x[2]=10;
x[3]=20;
cout<<x[0]<<x[1]<<x[2]<<x[3]<<endl;
char c[]={'g','\0','h'};
cout<<c[0]<<c[1]<<c[2];
}

OUTPUT

311020
g h

28
Aryaf Aladwan
#include <iostream.h>
void main()
{
int a=3,b=2;
int z[6]={1,2,3,4,5,6};
z[a+b]+=2;
z[0]=2;
z[4]=(a/b+6);
for (int i=0;i<=5;i++)
cout<<z[i]<<" ";

OUTPUT

2 2 3 4 7 8

29
Initialization using for loop
#include<iostream.h>
void main()
{
int a[6];
for (int i=0;i<=5;i++)
{
a[i]=i*i+1;
cout<<"a["<<i<<"]="<<a[i]<<endl;
}
}

OUTPUT
a[0]= 1
a[1]= 2
a[2]= 5
a[3= 10
a[4]= 17
a[5]= 26
30
Aryaf Aladwan
Initialization using while loop
#include<iostream.h>
void main()
{
int i=0;
int a[5]={0,1,2,3,4};
while(i<=5)
{
cout<<"a["<<i<<"]="<<a[i]*2<<endl;
i++;
}
}
OUTPUT
a[0]= 0
a[1]= 2
a[2]= 4
a[3= 6
a[4]= 8
31
Aryaf Aladwan
Character Arrays
#include<iostream.h>
void main()
{
char x[5]={‘A',‘H',‘M',‘E',‘D'};
for( int i=0;i<=4;i++)
{
x[i]++;
cout<<x[i]<<endl;
}
}
OUTPUT Note

B i=1 to i<=3
I I
N N
F F
E
32
Aryaf Aladwan
Examples Using Arrays

• Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

33
Aryaf Aladwan
Examples Using Arrays

• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables

34
Aryaf Aladwan
Array I/O programming
#include<iostream.h>
#define n 3 // const int n = 3
void main()
{
int z[n];
cout<<"Enter z[0]=";
cin>> z[0];
cout<<"Enter z[1]=";
cin>>z[1];
cout<<"Enter z[2]=";
cin>>z[2];
for (int i=0;i<=2;i++)
cout<<z[i]<<" ";
}

OUTPUT
Enter z[0] = 33
Enter z[1] = 19
Enter z[2] = 22
35 33 19 22
Aryaf Aladwan
Array I/O programming
#include<iostream.h>
void main()
{
int z[5];
int j;
for (j=0;j<=4;j++)
{
cout<<"Enter z["<<j<<"]";
cin>>z[j];
}
}

OUTPUT
Enter z[0] = 6
Enter z[1] = 3
Enter z[2]= 9
Enter z[3]= 7
Enter z[4]= 1
36
Aryaf Aladwan
#include<iostream.h>
void main()
{
int a[10],max,min,sum=0;
long int product=1; Write a program
cout<<"enter array elements\n"; to find the total,
cin>>a[0]; product,
max=a[0]; maximum and
min=a[0]; minimum of array
sum=sum+a[0];
elements?
product=product*a[0];
for (int i=0;i<=8;i++)
{
cin>>a[i];
sum= sum + a[i];
product= product * a[i];
if (max < a[i])
max = a[i];
if (min > a[i])
min = a[i];
}
cout<<"\n sum of array elements is :"<<sum;
cout<<"\n product of array elements is :"<<product;
cout<<"\n maximum number in the array is :"<<max;
cout<<"\n minimum number in the array is :"<<min;
}
37
Aryaf Aladwan
Output

38
Aryaf Aladwan
Write a program to find a product of two arrays
#include <iostream.h>
void main()
{
int array1[10],array2[10],result[10];
cout<<"enter the first array"<<endl;
for (int y=0;y<=9;y++)
cin>>array1[y];

cout<<"enter the second array"<<endl;


for (int f=0;f<=9;f++)
cin>>array2[f];

cout<<"the product of the two arrays are:"<<endl;


for (int k=0;k<=9;k++)
{
result[k]=array1[k]*array2[k];
cout<<result[k]<<" ";
}
}

39
Aryaf Aladwan
40
Aryaf Aladwan
41
Aryaf Aladwan
42
Aryaf Aladwan
43
Aryaf Aladwan
44
Aryaf Aladwan
45
Aryaf Aladwan
46
Aryaf Aladwan
47
Aryaf Aladwan
48
Aryaf Aladwan
49
Aryaf Aladwan
50
Aryaf Aladwan
51
Aryaf Aladwan
52
Aryaf Aladwan
53
Aryaf Aladwan
Multiple-Subscripted Arrays (two dimensional array)
(matrices)

• Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
a[0][0] is the first element of that array

Column 0 Column 1 Column 2 Column 3


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

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

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

Column subscript

Array name
Row subscript
54
Aryaf Aladwan
55
Aryaf Aladwan
56
Aryaf Aladwan
57
Aryaf Aladwan
58
Aryaf Aladwan
59
Aryaf Aladwan
60
Aryaf Aladwan
61
Aryaf Aladwan
Multiple-Subscripted Arrays Initialization

• To initialize
– Default of 0
– Initializers grouped by row in braces 1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
Row 0 Row 1

a b
char x[2][2]={{’a’ ,’b’} ,{’c’ ,’d’}};
c d

a b
char x[2][2]={{″ab” ,”cd”}};
c d

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0
3 4

62
Aryaf Aladwan
Multiple-Subscripted Arrays

• To initialize
– Default of 0
1 2
– Initializers grouped by row in braces 3 4
int b[ 3 ][ 2 ] = { {1,2,3,4}}; 0 0

1 2
4 0
int b[ 3 ][ 2 ] = { {1,2},{4}};
0 0

63
Aryaf Aladwan
64
Aryaf Aladwan
65
Aryaf Aladwan
66
Aryaf Aladwan
67
Aryaf Aladwan
68
Aryaf Aladwan
69
Aryaf Aladwan
70
Aryaf Aladwan
71
Aryaf Aladwan
Printing two dimensional arrays

#include <iostream.h>
void main()
{
OUTPUT
int a [2][3] = {2, 5};
for (int r = 0 ; r < 2 ; r++)
{
2 5 0
for (int c = 0; c < 3 ; c++)
{ 0 0 0
cout<< a[r][c] << "\t";
}
cout << "\n";
}
}

72
Aryaf Aladwan
Initializing array elements with calculations

#include <iostream.h>
void main()
{
OUTPUT
int Z[3][3];
for (int r = 0 ; r < 3 ; r++)
{
0 1 2
for (int c = 0; c < 3 ; c++)
{ 1 2 3
Z[r][c] = r + c ;
2 3 4
cout<< Z[r][c] << ”\t”;
}
cout << ”\n”;
}
}

73
Aryaf Aladwan
Summing the array elements

#include <iostream.h>
void main()
{
int marks [3][3] = {91, 88, 71, 84, 66, 99, 69, 79, 81};
int sum = 0;
for (int r = 0 ; r < 3 ; r++)
{
for (int c = 0; c < 3 ; c++)
{
sum += marks[r][c];
}
}
cout << "Total = " << sum
}

OUTPUT

Total = 728
74
Aryaf Aladwan
#include<iostream.h>
void main()
{
char a[3][3]={{1, 2, 3} ,{4 ,5 ,6} ,{7 ,8 ,9}};
for (int n=0;n<3;n++)
{
for (int m=0;m<3;m++)
OUTPUT
{
a[n][0]+=2;
a[2][m]--; 3 2 3
cout<<a[n][m]<<" "; 6 5 6
}
cout<<endl;
6 5 6
}
}

75
Aryaf Aladwan
#include<iostream.h>
void main()
{
char a[3][3]={{'k', 'b', 'c'} ,{'d‘ ,'e‘ ,'w'} ,{'m‘ ,'n‘ ,'s'}};
for (int n=0;n<3;n++)
{
for (int m=0;m<3;m++)
{ OUTPUT
a[n][0]+=2;
a[2][m]--; m b c
cout<<a[n][m]<<" "; f e w
}
cout<<endl;
l k p
}
}

76
Aryaf Aladwan
77
Aryaf Aladwan
78
Aryaf Aladwan
79
Aryaf Aladwan
Fundamentals of Characters and Strings

• Character constant
– Integer value represented as character in single quotes
– 'z' is integer value of z
• 122 in ASCII
• String
– Series of characters treated as single unit
– Can include letters, digits, special characters +, -, * ...
– String literal (string constants)
• Enclosed in double quotes, for example:
"I like C++"
– Array of characters, ends with null character '\0'
– String is constant pointer
• Pointer to string’s first character
– Like arrays
80
Aryaf Aladwan
Fundamentals of Characters and Strings

• String assignment
– Character array
• char color[] = "blue";
– Creates 5 element char array color
• last element is '\0'

– Alternative for character array


• char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };

81
Aryaf Aladwan
Cont.

• Reading strings

– Assign input to character array word[ 20 ]


cin >> word
• Reads characters until whitespace or EOF

82
Aryaf Aladwan
83
Aryaf Aladwan
84
Aryaf Aladwan
85
Aryaf Aladwan
86
Aryaf Aladwan
String Manipulation Functions of the String-
handling Library

• String handling library <string.h> provides


functions to :
– Manipulate string data
– Compare strings
– Search strings for characters and other strings
– Tokenize strings (separate strings into logical pieces)

87
Aryaf Aladwan
88
Aryaf Aladwan
String Manipulation Functions of the String-
handling Library

strcpy( char s1, char s2 ) Copies the string s2 into the character
array s1. The value of s1 is returned.
strncpy (char s1, char s2, int n ) Copies at most n characters of the string s2
into the character array s1. The value of s1 is
returned.

strcat( char s1, char s2 ) Appends the string s2 to the string s1. The
first character of s2 overwrites the terminating
null character of s1. The value of s1 is
returned.

strncat( char s1,char s2, int n ) Appends at most n characters of string s2 to


string s1. The first character of s2 overwrites
the terminating null character of s1. The value
of s1 is returned.

89
Aryaf Aladwan
90
Aryaf Aladwan
91
Aryaf Aladwan
92
Aryaf Aladwan
93
Aryaf Aladwan
94
Aryaf Aladwan
95
Aryaf Aladwan
String Manipulation Functions of the String-
handling Library

strcmp (char s1,char s2 ) Compares the string s1 with the string s2.
The function returns a value of zero or -1 or 1
if s1 is equal to s2 , less than s2 or greater
than s2, respectively.

strncmp(char s1, char *s2, int n ) Compares up to n characters of the string s1


with the string s2.
The function returns a value of zero or -1 or 1
if s1 is equal to s2 , less than s2 or greater
than s2, respectively. .

strlen( char s ) Determines the length of string s. The


number of characters preceding the
terminating null character is returned.

96
Aryaf Aladwan
97
Aryaf Aladwan
98
Aryaf Aladwan
99
Aryaf Aladwan
100
Aryaf Aladwan
101
Aryaf Aladwan
102
Aryaf Aladwan
103
Aryaf Aladwan
104
Aryaf Aladwan
105
Aryaf Aladwan
106
Aryaf Aladwan
107
Aryaf Aladwan
Example of strlen , strcpy and strncpy
#include <iostream.h>
#include <string.h>
void main()
{
char x[] = "Happy Birthday to You";
char y[ 25 ];
char z[ 15 ];
cout<< strlen(x);
strcpy( y, x ); // copy contents of x into y
cout << "string in array x is: " << x << endl;
cout << "string in array y is: " << y << '\n';
// copy first 14 characters of x into z
strncpy( z, x, 11 ); // does not copy null character
z[ 11 ] = '\0'; // append '\0' to z's contents
cout << "string in array z is: " << z << endl;
}

OUTPUT 21
The string in array x is: Happy Birthday to You
108 The string in array y is: Happy Birthday to You
The string in array z is: Happy Birth
Example of strcat and strncat
#include <iostream.h>
#include <string.h>
void main()
{
char s1[ 20 ] = "welcome ";
char s2[] = "in fet ";
char s3[ 40 ] = "";
cout << "s1 = " << s1 <<endl<<"s2 = " << s2<<endl;
strcat( s1, s2 ); // concatenate s2 to s1
cout << "After strcat(s1, s2): " << endl;
cout<< "s1 = " << s1 <<endl<< "s2 = " << s2<<endl;
// concatenate first 6 characters of s1 to s3
strncat( s3, s1, 6 ); // places '\0' after last character
cout<<"s3 = "<<s3;
}

OUTPUT s1 = welcome
s2 = in fet
After strcat(s1, s2):
s1 = welcome in fet
109
s2 = in fet
s3 = welcom
Example of strcmp and strncmp

#include <iostream.h>
#include <string.h>
void main()
{
char m[]="Apple";
char a[]="Table";
char z[]="Apple";
char b[]="TableAndChair";
cout<<strcmp(m,a)<<"\n"<<strcmp(a,m)<<"\n";
cout<<strcmp(m,z)<<"\n"<<strcmp(a,b)<<endl;
cout<<strncmp(a,b,5)<<"\n"<<strncmp(b,a,6 );
}

OUTPUT
-1
1
0
-1
110 0
1
Assignment
• Write a program for an exam which has 20 multiple choice questions.
Here are the correct answers:

1. b
2. d
3. a
4. a
5. c
6. a
7. b
8. a
9. c
10. d
11. b
12. c
13. d
14. a
15. d
16. c
17. c
18. b
19. d
20. a

111
Aryaf Aladwan
Assignment

• Your program should store the answers shown above


in an array. It should then ask the user to enter the
student's answers for each of the 20 questions, which
should be stored in another array. After the student's
answers have been entered, the program should
display a message indicating whether the student
passed or failed the exam. If he passed (A student
should answer 15 of the 20 questions correctly to pass
the exam.) print pass and display the total number of
correctly answered questions. If he failed print fail.

112
Aryaf Aladwan
113
Aryaf Aladwan
114
Aryaf Aladwan
End

115
Aryaf Aladwan

You might also like