Você está na página 1de 17






Array is the collection of data storage locations, each of which holds the same type of data. Each storage location is called the element of the array. The basic idea behind the array is to group together similar data items. In array all the data storage locations should have same data type. The array is the convenient way to group together hundred or even thousands of data item. Each element in the array is stored on a particular location. The array can be of one dimension or multidimensions. The one dimensional array is just a series of data items. Declaring the Array Like variables and functions the array is also first declared so that the compiler comes to know that what sort of code is that. Array is declared by writing its data type first which tells the compiler that all the elements in this array will hold particular data type. Then the array name follows, which follows the same rules of identifier then in the square brakets the index or subscript or array size is used which tells the compiler that how many number of data items will the array can hold. Note that the index is always in integer numbers because the item numbers can only be in the whole number form.

int MyArray[10];
In the above array declaration the array named as MyArray is declared with the integer data type which tells that all the elements of this array will hold the integer values and the 10 in the square brackets is the index/array size/subscript which tells that this array will hold 10 integer data items. Note that the array counts the data item form 0 so; in this array the data item will be located at the positions from 09.

Data type of array Name of array Size of array

int MyArray[10];

Array Elements The data storage locations/items in an array are referred as the array elements and they all posses same data type. These array elements are responsible for storing certain data in to them. In an array the array elements start from the location 0 (zero) and onwards. Let an array named mass contains 5 data items each having floating point data type and values then;

mass[0]=10.1 is first data item containing value 10.1, mass[1]=20.4 is second data item containing value 20.4, mass[2]=8.7 is third data item containing value 8.7, mass[3]=5.9 is fourth data item containing value 5.9 and mass[4]=0.01 is fifth data item containing value 0.01.

int mass[5];
10.1 20.4 8.7 5.9 0.01

mass[0] mass[1] mass[2] mass[3] mass[4]

You can also initialize the array elements by assigning them the values after declaring the array as,

int number[7]; number[0]=10; number[1]=30; number[2]=17; number[3]=67; number[4]=54; number[5]=14; number[6]=19;

Note that when you are initializing the array elements you dont have to give the data type but you have to give in the array declaration.

Accessing array elements After you have set the values to the array elements now you can access them by using the subscriptits location in the array. To access the particular location/element write the array name followed by the subscript in the square brackets as,

cout<<number[5]; OR int a=5; cout<<number[a];

In the above statements the element at the location number 5 is accessed from the array number. You can also use the variable or expression in the subscript which evaluates a single integer data type number as the variable a in above declaration does. Note the difference that in array declaration we use data type but when we are accessing certain element of the array we dont have to give the data type. Initializing the Array Initializing the array means setting the values to the array elements at the time of writing the program. Like variables you can also give certain values to the array elements. To do this the values are assigned to the array by placing an equal to sign and placing the values in the curly bracket separated by comma following the equal to sign as,

int MyArray[]={10, 20, 30, 40, 50}; int MyArray[5]={10, 20, 30, 40, 50};
In above initialization the array MyArray is initialized with 5 values so, 10 20 30 40 50 will will will will will be be be be be assigned assigned assigned assigned assigned to to to to to

MyArray[0], MyArray[1], MyArray[2], MyArray[3] and MyArray[4].

It is optional that you place the array size in the array initialization or not . But assigning the value more than the array size is not in the interest of the compiler.

int MyArray[4]={10, 20, 30, 40, 50}; //Compiler will complain int MyArray[8]={10, 20, 30, 40, 50}; //It is legal but not recommended

Program (array1.cpp)
#include <iostream.h> #include <conio.h> void main() { float temp[5]; float sum=0.0, average=0.0; for(int i=0; i<5; i++) { cout<<Enter the temperature <<i+1<< : ; cin>>temp[i]; cout<<endl; } for(i=0; i<5; i++) sum+=temp[i]; average=sum/5; cout<<endl<<The average temperature is : <<average; getch(); } Output: Enter the temperature 1 : 37.7 Enter the temperature 2 : 35.9 Enter the temperature 3 : 27.5 Enter the temperature 4 : 39.1 Enter the temperature 5 : 38.6 The average temperature is : 35.760002

Multidimensional Array As we saw that the one dimensional array is a series of elements stored into the array but the array can also contain multiple dimensions as two, three and so on. In two dimensional arrays two subscripts are used, in three dimensional arrays three subscripts are used and the sequence continues.

int MultiArray2[2][2]; int MultiArray3[3][2][5]; int MultiArray5[2][3][7][3][5];

//Two Dimensional Array //Three Dimensional Array //Five Dimensional Array

Initializing Multidimensional (Two-Dimensional) Array elements Like one dimensional array you can also initialize the multidimensional array but the difference is only that in multidimensional element the location of the elements is nested into the subscripts. The two dimensional array behaves as the matrix having rows and columns.

int TwoDim[3][3]=25;
The above declaration assigns the value 25 to the element in the 3 rd location of the 3rd location of the fist subscript. This means that the locations in the multidimensional arrays are nested in to the subscripts.

0 0 1 2 3

0 0 0
3 0

0 0 0 0

0 0 0 0

0 0 0 25


Strings in C++ String is the collection/sequence of characters. In C++ we can work with strings by either using the character array or the predefined string class. In character data type only single byte of the memory is occupied while in string multiple number of bytes of memory are engaged. Character Array (C-String) Character array is the simple array with the data type of char used to hold the strings/sequence of characters. These strings are also known as C-String because they were only the kind of strings available in C language and in early version of C++ language. The array variable used to hold the string is known as C-String. To declare CString variable, as traditionally, we use the data type in front of the C-String variable but the data type must be type char. Then in square bracket the size of the string is initialized. As for each character 1 byte of the memory is engaged, but in strings special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Hence if a string has n characters then it requires an n+1 element array (at least) to store it. Thus the character `a' is stored in a single byte, whereas the single-character string "a" is stored in two consecutive bytes holding the character `a' and the null character. Lets examine the below program:

Program (CString.cpp)
#include <iostream.h> #include <conio.h> void main() { char string1[7]; cout<<Enter the string: ; cin>>string1; cout<<Your string is: <<string1; getch(); }
Firstly the program will initialize the C-String variable string1 holding 7 elements. Now say you have entered Asghar then this string will occupy 6 memory locations of the character array and the 7th location will be occupied by the num character \0. Finally the cout statement will sent the string string1 to the console screen.

Array of Strings In an string array you can store array of sequence of characters. String array is the two dimensional array in which first dimension tells how many strings will be stored in the string array and the second dimension tells about how many characters each string will hold. Lets examine the below program:

Program (ArrayString.cpp)
#include <iostream.h> #include <conio.h> void main() { char day[7][11]={ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; for(int i=0; i<7; i++) cout<<Day <<i+1<< : <<day[i]<<endl; getch(); }

In the above program the array day is initialized with the two dimensions. First dimension declares the number of strings to be store in the array day and the second dimension determines the number of characters in each string to be store, 11 in this program which are enough to store the name of any day. In the cout statement you will find that there is only single dimension used and in the declaration we have initialized two dimensions then what happened to the other dimension. As we know that two dimensional array is the nested array (array of arrays) so we can access each outer array containing the entire element for this we use only single index.

The Standard C++ String Class As previously we used to store the string in the arrays so it was very complicated, time consuming and stretching. So the standard C++ includes a string class which defines an easy way to store and access the strings. The string class also offers many advantages as you can also concatenate(combine) two or more strings. The String class is more safer and convenient way to store the strings and work with them then the C-Strings. Declaring and Defining the string Objects You can declare the string object by using the keyword string with some variable then the variable used will hold the data type of type string and can store the string of any length. To define or assign the string object we place the string constant in the double quotation marks followed by the equal to sign after the string object. You can also define and string object by placing the string constant in the parenthesis delimited by the double quotation marks. You can also assign one string object to another string object by using the arithmetic operator +. It is just like grouping two or more strings in one string object. Note that working with string objects you should have access to the string.h and cstring.h header files. Therefore you should first include the header files string.h and cstring.h at the top of your program.

string s1; string s2=Ali Asghar; string s3(Ali Asghar);

//Declaring string object //Defining string object way 1 //Defining string object way 2

Program (StringClass1.cpp)
#include #include #include #include <iostream.h> <conio.h> <string.h> <cstring.h>

void main() { string s1=Ali ; string s2=Asghar; string s3; s3=s1+s2; cout<<s3; getch();

In the above program the string objects s1 and s2 are defined and assigned with some string constant, s1 is assigned with the string constant Ali and s2 is assigned with the string constant Asghar. Then third string object s3 is declared and is assigned to the combination of the string objects s1 and s2 so the string object s3 will contain the both s1 and s2. Inputting string objects with getline() As inputting character array we used the function cin.get() but when inputting string objects we have a different structure. The function used to input string objects is the getline() function which gets the string from the user and puts in the desired string object. The syntax for the getline() function is as,

getline(cin, stringObject); getline(cin, stringObject, character);

//Syntax 1 //Syntax 2

In Syntax 1 the function has two arguments first is cin and the other is for the string object in which the string will be placed. In Syntax 2 the function has three arguments, the first is cin, the second is for the string object and the third argument gets any character which when entered during the string input will terminate the string input.

Program (getline.cpp)
#include #include #include #include <iostream.h> <conio.h> <string.h> <cstring.h>

void main() { string s1, s2; cout<<Enter your names : ; getline(cin, s1,$); cout<<Enter your cast : ; getline(cin, s2); cout<<Your full name: <<(s1+s2); getch(); }

1. Write a program using array that asks user to input any 10 numbers; the program then sorts the numbers in ascending order and displays the sorted numbers. 2. Write a C++ program that gets 10 numbers entered by the user. The program also asks the user to give any number to find it in the array, and passes the array and the number (that is to be found) to a function as argument; the function displays the result that whether number found or not. 3. Write a program that gets time in hours, minutes and seconds from the user, convert the time into seconds using function. The function takes hours, minutes and seconds as arguments and returns the time in seconds.

4. Write a program that gets user name (in an array), then swaps the entered name
using two functions one for getting input and other for swapping the name. For example if user enters NAEEM, the swap function reverses the letters to MEEAN. 5. Write a program that asks user to enter two fractions say a/b and c/d; and then displays the sum in fractional form. For example:

Enter First Fraction: 1/2 Enter Second Fraction: 2/5

Sum = 9/10 6. Write a program using array that gets 10 numbers from the user. This program calculates the average of those numbers. Use function that computes the average of those numbers and return the average value.


Program # 01
#include <constream.h> void main() { int num[10], temp; for(int i=0; i<10; i++) { cout<<"Enter number "<<i+1<<" : "; cin>>num[i]; } for(i=0; i<9; i++) { for(int j=i+1; j<10; j++) { if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } } } for(i=0; i<10; i++) cout<<num[i]<<endl; getch(); }


Program # 02
#include <constream.h> void location(int array[], int number); void main() { clrscr(); int numb[10], search; for(int i=0; i<10; i++) { cout<<"Enter the numbers "<<i+1<<" : "; cin>>numb[i]; } cout<<"Enter the number to find its location : "; cin>>search; location(numb, search); getch(); } void location(int array[], int number) { int found=0; for(int i=0; i<10; i++) { if(number==array[i]) { found=1; cout<<"The number found at the location : "<<i; } } if(found==0) cout<<"Number not found at any location."; }


Program # 03
#include <constream.h> long time(int hrs, int min, int sec); void main() { clrscr(); int hours, minutes, seconds; cout<<"Enter the time:"<<endl; cout<<"Hours : "; cin>>hours; cout<<"Minutes : "; cin>>minutes; cout<<"Seconds : "; cin>>seconds; cout<<"The time in seconds is : "<<time(hours, minutes, seconds); getch(); } long time (int hrs, int min, int sec) { int total_sec=0; total_sec=((hrs*3600)+(min*60)+(sec)); return (total_sec); }


Program # 04
#include<constream.h> #include <string.h>

char name[15]; void getname(); void swapname();

void main() { clrscr(); getname(); swapname(); getch(); }

void getname() { cout<<"Enter your name: "; cin>>name; }

void swapname() { for(int i=strlen(name); i>=0; i--) cout<<name[i]; }



Program # 05
#include <constream.h> void main() { clrscr(); int a, b, c, d, numerator, denomenator; char dummychar; cout<<"Enter first fraction: "; cin>>a>>dummychar>>b; cout<<"Enter first fraction: "; cin>>c>>dummychar>>d; numerator=(a*d)+(b*c); denomenator=b*d; cout<<"Sum = "<<numerator<<dummychar<<denomenator; getch(); }



Program # 06
#include <constream.h> const int SIZE=10; float average(int array[], int total_elements); void main() { clrscr(); int numb[SIZE]; for(int i=0; i<SIZE; i++) { cout<<"Enter the number "<<i+1<<" : "; cin>>numb[i]; } cout<<"The average is : "<<average(numb, SIZE); getch(); }

float average(int array[], int total_elements) { int sum=0, average=0.0; for(int i=0; i<total_elements; i++) sum+=array[i]; average=sum/total_elements; return (average); }