PF Ue Lec 6
PF Ue Lec 6
(COMP1112)
Arrays
• You don't have to specify the size of the array. It will be as big as the
elements that are inserted into it:
string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is 3
Example- calculating average of 10 numbers
int main()
{
int i;
float num[10], sum=0.0, average;
for(i = 0; i < 10; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / 10;
cout << "Average = " << average;
return 0;
}
Example- Finding largest element of array
int i, n;
float arr[10];
cout << "Enter total number of elements: ";
cin >> n;
for(i = 0; i < n; ++i)
{
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
// Loop to store largest number to arr[0]
for(i = 1;i < n; ++i)
{ if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "Largest element = " << arr[0];
Example- take 5 numbers in array from user
and display those in reverse order
int arr[5];
for(int i = 0; i < 5; ++i)
{
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
cout << "reverse order"<<endl;
for(int i = 4;i>=0; i--)
{
cout << arr[i];
}
Array of characters
Two ways of declaration and initialization:
• char name[]="khan ali";
• char name2[]={'a','b','c'};
• Object oriented programming using C++ by Tasleem Mustafa, Imran Saeed, Tariq Mehmood, Ahsan Raza
• https://www.tutorialspoint.com/cplusplus
• http://ecomputernotes.com/cpp/introduction-to-oop
• http://www.cplusplus.com/doc/tutorial
• https://www.guru99.com/c-loop-statement.html
• www.w3schools.com