You are on page 1of 13

Arrays

Lecture # 09
Arrays to Strings
Arrays of string
 Just like numbers we can have string in an array
 For Example:
int main()
{
    // Initialize String Array
    string colour[4] = {"Blue", "Red", "Orange", "Yellow"};
      
    // Print Strings
    for (int i = 0; i < 4; i++) 
       { cout << colour[i] << "\n"; }
}
Loop Through an Array
You can loop through the array elements with the
for loop.
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++)
output
{ Volvo
cout << cars[i] << "\n"; BMW
} Ford
Mazda
The following example outputs the index of each
element together with its value:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++)
output
{
0: Volvo
cout << i << ": " << cars[i] << "\n"; 1: BMW
} 2: Ford
3: Mazda
Copying Array Elements
Procedure to copy elements of one
array to another in C++
1. Create an empty array.
2. Insert the elements.
3. Create a duplicate empty array of the same size.
4. Start for loop i=0 to i=array length.
5. newarray[i]=oldarray[i]
6. end for loop
Copying from Integer Array to Another
#include<iostream>
using namespace std;
int main() {
int arr1[10]={10,20,30,40,50,60,70,80,90,100};
int arr2[10];
for (int i = 0; i < 10; i++)
{ arr2[i] = arr1[i]; }
cout << "\nCopy Array List is :";
for (int i = 0; i < 10; i++)
{ cout << arr2[i] << " "; }
}
Copying from String Array to another
int main() {
string str[4] = {"Good", "Bad", "Positive", "Negative"};
string s[4];
for( int i=0; i<4; i++) {

s[i] = str[i];
}
for(int i=0; i<4; i++) {
cout << "The element " << i+1 << " of copied array = " << s[i]
<< " is same as " << str[i] << endl;
}
}
Self Test Exercise
Note Arrays can be passed to functions
Consider the following function definition:
void tripler(int n[])
{ n = 3*n; }
Which of the following are acceptable function calls?
int a[3] = {4, 5, 6}, number = 2;
1. tripler(number);
2. tripler(a[2]);
3. tripler(a[3]);
4. tripler(a[number]);
5. tripler(a);
Self Test Exercise
Note Arrays can be passed to functions
Consider the following function definition:
void too2(int a[], int how_many)
{ for (int index = 0; index < how_many; index++)
a[index] = 2; }
Which of the following are acceptable function calls?
int my_array[29];
1. too2(my_array, 29);
2. too2(my_array, 10);
3. too2(my_array, 55);
4. “Hey too2. Please, come over here.”
5. int your_array[100];
6. too2(your_array, 100);
7. too2(my_array[3], 29);
Find if there exist any error
int main()
{
int crash[10], i;
for(i=0; i<100; i++)
{
crash[i] = i;
}
cout<<“DONE”;
}
Find an Error
 #include<iostream>
 using namespace std;
 int main() {
 int A1[15]={10,20,30,40,50,60,70,80,90,100};
 int A2[10];
 for (int i = 0; i < 10; i++)
 { A2[i] = A1; }
 cout << "\nCopy Array List is :";
 for (int i = 0; i < 10; i++)
 { cout << A2[i] << " "; }
 }

You might also like