understanding array by dk mamonai 09ce37

Upload: darya-memon

Post on 07-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    1/17

    Data type of array

    Name of array

    Size of array

    OBJECT: TOBECOMEFAMILIARWITH ARRAYSANS STRINGS.

    Array

    Array is the collection of data storage locations, each of which holds the same type ofdata. Each storage location is called the element of the array. The basic idea behind thearray is to group together similar data items. In array all the data storage locationsshould have same data type. The array is the convenient way to group together hundredor even thousands of data item. Each element in the array is stored on a particularlocation. The array can be of one dimension or multidimensions. The one dimensionalarray 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 toknow that what sort of code is that. Array is declared by writing its data type first whichtells the compiler that all the elements in this array will hold particular data type. Thenthe array name follows, which follows the same rules of identifier then in the squarebrakets the index or subscript or array size is used which tells the compiler that howmany number of data items will the array can hold. Note that the index is always ininteger 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 andthe 10 in the square brackets is the index/array size/subscriptwhich tells thatthis array will hold 10 integer data items. Note that the array counts the data item form0 so; in this array the data item will be located at the positions from 09.

    int MyArray[10];

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    2/17

    Array Elements

    The data storage locations/items in an array are referred as the array elements and theyall posses same data type. These array elements are responsible for storing certain datain to them. In an array the array elements start from the location 0 (zero) and onwards.Let an array named

    masscontains 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];

    You can also initialize the array elements by assigning them the values after declaringthe 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 datatype but you have to give in the array declaration.

    10.1

    20.4

    8.7

    5.9

    0.01

    mass[0]

    mass[1]

    mass[2]

    mass[3]

    mass[4]

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    3/17

    Accessing array elements

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

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    4/17

    Program (array1.cpp)

    #include #include

    void main(){float temp[5];float sum=0.0, average=0.0;

    for(int i=0; i

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    5/17

    Multidimensional Array

    As we saw that the one dimensional array is a series of elements stored into the arraybut 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 subscriptsare used and the sequence continues.

    int MultiArray2[2][2]; //Two Dimensional Arrayint MultiArray3[3][2][5]; //Three Dimensional Arrayint MultiArray5[2][3][7][3][5]; //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 nestedinto the subscripts. The two dimensional array behaves as the matrix having rows andcolumns.

    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 multidimensionalarrays are nested in to the subscripts.

    0 1 2 3

    0

    1

    2

    3 3

    0

    0

    0

    0

    TwoDim[3][3]=25

    0

    0

    0

    0

    0

    0

    0

    0

    0

    0

    0

    25

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    6/17

    Strings in C++

    String is the collection/sequence of characters. In C++ we can work with strings byeither using the character arrayor the predefined string class. In character data

    type only single byte of the memory is occupied while in string multiple number of bytesof 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-Stringbecause theywere 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 C-String variable, as traditionally, we use the data type in front of the C-String variablebut 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 specialnull character, represented by `\0', is appended to the end of the string to indicate theend of the string. Hence if a string has n characters then it requires an n+1 elementarray (at least) to store it. Thus the character `a' is stored in a single byte, whereas thesingle-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 #include

    void main(){

    char string1[7];

    coutstring1;

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    7/17

    Array of Strings

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

    Program (ArrayString.cpp)

    #include

    #include

    void main()

    {

    char day[7][11]={ Monday, Tuesday, Wednesday, Thursday,

    Friday, Saturday, Sunday};

    for(int i=0; i

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    8/17

    The Standard C++ String Class

    As previously we used to store the string in the arrays so it was very complicated, timeconsuming 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 advantagesas you can also concatenate(combine) two or more strings. The String class is moresafer and convenient way to store the strings and work with them then the C-Strings.

    Declaring and Defining thestring 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 doublequotation 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 thedouble quotation marks.

    You can also assign one string object to another string object by using the arithmeticoperator +. 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 andcstring.hheader files. Therefore you should first include the header files string.hand cstring.hat the top of your program.

    string s1; //Declaring string object

    string s2=Ali Asghar; //Defining string object way 1

    string s3(Ali Asghar); //Defining string object way 2

    Program (StringClass1.cpp)

    #include #include #include #include

    void main(){

    string s1=Ali ;string s2=Asghar;string s3;s3=s1+s2;cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    9/17

    }

    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 withthe 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 stringobjects we have a different structure. The function used to input string objects is thegetline() 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); //Syntax 1

    getline(cin, stringObject, character); //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 thestring input will terminate the string input.

    Program (getline.cpp)

    #include #include #include #include

    void main(){

    string s1, s2;

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    10/17

    EXERCISE

    1. Write a program using array that asks user to input any 10 numbers; the programthen 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 thenumber (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. Forexample 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 thendisplays the sum in fractional form.For example:

    Enter First Fraction: 1/2

    Enter Second Fraction: 2/5Sum = 9/10

    6. Write a program using array that gets 10 numbers from the user. This programcalculates the average of those numbers. Use function that computes the average of

    those numbers and return the average value.

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    11/17

    EXERCISESOLUTIONS

    ===================================================

    Program # 01

    #include

    void main(){

    int num[10], temp;

    for(int i=0; i

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    12/17

    ===================================================

    Program # 02

    #include

    void location(int array[], int number);

    void main(){

    clrscr();int numb[10], search;

    for(int i=0; i

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    13/17

    ===================================================

    Program # 03

    #include

    long time(int hrs, int min, int sec);

    void main()

    {

    clrscr();

    int hours, minutes, seconds;

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    14/17

    ===================================================

    Program # 04

    #include

    #include

    char name[15];

    void getname();

    void swapname();

    void main()

    {

    clrscr();

    getname();

    swapname();

    getch();

    }

    void getname()

    {

    coutname;

    }

    void swapname()

    {for(int i=strlen(name); i>=0; i--)

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    15/17

    ===================================================

    Program # 05

    #include

    void main()

    {

    clrscr();

    int a, b, c, d, numerator, denomenator;char dummychar;

    couta>>dummychar>>b;

    coutc>>dummychar>>d;

    numerator=(a*d)+(b*c);

    denomenator=b*d;

    cout

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    16/17

    ===================================================

    Program # 06

    #include

    const int SIZE=10;

    float average(int array[], int total_elements);

    void main()

    {

    clrscr();

    int numb[SIZE];

    for(int i=0; i

  • 8/6/2019 Understanding Array by Dk Mamonai 09CE37

    17/17

    ===================================================