Translate

Saturday 19 May 2012

1 - Dimensional array in C++


     It is an array having array name followed by subscript or index endosed within brackets [ ].
Declaration:- storage class datatype array-name[subscript];
where the storage class specifies the default initialization and the life periodof the array. The datatype indicates the type of list to be assigned with the array. Array name is an identifier. Subscript specifies the size of the array. The subscript should be a constant.
    Example:- int a[10];
                    float f[m];  where m is a constant.

Initialisation of array:- Like an ordinary variable an array variable can be initialized with one or more values.
      Example:- int a[4]={1,2,3,4}
The values are assigned with the array variable as listed below
           a[0]=1,a[1]=2, a[2]=3, a[3]=4
Always remember the first variable of array has subscript 0.
     If the size of an array is ‘n’ and initialised with less than n values then the remaining positions will be filled with 0. For instance an array has the size of 10 and is initialized with 4 values than the last 6 positions are filled with 0.
    When an array is initialised with list of n values the size of the array need not be specified.
           int a []= {1,2,3,4};
The size should be specified when an array is not initialised with a list.


Q. Write a program to display first n terms of Fibonacci series by using array variable where
fn = fn-1 + fn-2
#include<iostream>
#include<iomanip.h>
void main()
{
     int f [50], n;
     cout<< “Enter the size of list”;
     cin>>n;
     for(int i=1;i<n; i++)
     {
           f [i]= i < 2  ?  1  :  f [i-1] + f [i-2];
           cout<<  setw(5) <<  f [i];
     }
}

Q. Correct the error in following program segment.
void main()
{
     int x[ ]=(3, 9, 15, 21);
     for (i=0, i<4, i++)
          cout { x[i];
};

Answer:-
void main()
{
     int x[ ]=3, 9, 15, 21};
     for( int i=0; i<4; i++)
          cout<< x[i];
}


No comments:

Post a Comment

Total Pageviews