SlideShare a Scribd company logo
1 of 13
Download to read offline
Page 1 of 13
                                     Arrays and Library Functions

           Arrays: - An array is a collection of variables of the same type that are referenced by a common
           name. It consists of contiguous memory locations.

           Need for arrays:- For large applications or calculations say to find the average marks of 50
           students if we use 50 different variables the job will be cumbersome and tedious and program
           maintenance will be very difficult. But if we use array the remembering and managing these
           variables will be easy.
           To make the program complex –free and more understandable array is used.

           Declaration of arrays:
                                 Syntax:- data-type array-name[size];
                                 For ex:- int A[10];
                                          float B[20];
                                          char C[30];
           where data-type refers to any fundamental(or primitive or in-built) data types, array-name
           will be any valid identifier name and size will be any number which indicates no. of elements
           the array contains.

           Types of Arrays:- Arrays are of two types:- (i) one-dimensional arrays and (ii) Two-
           dimensional arrays. Both the arrays can be of numeric as well as character (or string) types.

            (i) One-dimensional (or single dimensional or 1-D) arrays:- It is         a collection of similar
           types of elements referenced by a common name. The elements of the         are referred by their
           subscripts or indices.
                  For eg. int A[5];
           The above array will be having elements : A[0], A[1], A[2], A[4], A[5].    Array subscripts ( the
           numbers which are within [ ] ) always starts with number 0 not 1 in        C++. Subscripts are
           the locations of the elements within the array.

           Memory representation of 1-D array

           Let us take the above example which is int A[5];

               A[0]     A[1]      A[2]         A[3]       A[4]         Location
Starting              25       -13        44          0          10
address                                                                           value
           Where A[0] is the first element, A[1] is the second element and so on. The last element (i.e. 10
           here) always having location A[size-1]. Each element contains 2 bytes of memory.
           The address of first element of the array i.e. &A[0] is called the base address of the array.

           Note:- The name of the array (here A) is a pointer to its base address i.e. first element’s
           address (i.e. &A[0]).

           Size of the array in memory = data-type X size of the array
           For the above array the memory occupied will be 2 X 5 = 10 bytes.
           We can find it using C++ coding also
                   cout << sizeof(A); here sizeof is a operator which is used to find the size of any data
           type, variable or derived data type in bytes and A is the array name.

           Initialization of One-dimensional array (Numeric type):- There are two types of
           initialization
                (i)     Sized array initialization and
                (ii)    unsized array initialization
           (i) Sized array initialization :- It can be done during the program writing (i.e. before program
           execution) or during the program execution (Using Loop).

           For ex:-     int A[5] = {12, 13, 20, 5, 2};
                                                  Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 13
               float B[4] = { 3.4, 4.5, 6.2, 7.8};
 This is sometimes called direct initialization.

 code segment:
                      int A[5];
                        for( int i=0; i<5; i++)
                       cin >> A[i];
 Here the values must be provided by the user during the execution of the program.
 In the first case the values are actually assigned during the compilation time and in the second
 case the values are assigned during the execution time by the user’s input.

 (i) Unsized array initialization :- It can only be done in following ways:

         int A[ ] = {2, 5, 17, 10, 12};     // No size is given within [ ]
         char str[ ] = “Kendriya Vidyalaya”;
 The compiler will automatically fixed the size of the array. Here the advantage is that the
 number of elements can be increased or decreased without considering the size. It is more
 flexible whenever there is a requirement of direct initialization or the values are known to the
 user.


 String as an array:- C++ does not string data types rather it implements string as one-
 dimensional character arrays.
 String is defined as a array of characters that is terminated by a null character ‘0’.
 For ex:- char str[20] = “Kendriya Vidyalaya”;
 It can be represented as
                                                           Location in the array
str[0]                                str[8]                                           str[18]
 K       e   n   d   r   i    y   a            V   i   d    y   a    l    a   y    a     0

 The above array contains 18 characters , but it can contain maximum of 19 characters i.e. size –
 1 characters and one space is reserved for null character. Here the length of the array is 18.
 The position of null character is not taken for finding the length of the array.

 (i) Two-dimensional (2-D) arrays:- A two-dimensional array is a multi one-dimensional
 arrays. It consists of rows and columns i.e. it is in a matrix format.
 For instance an array A[m][n] is an m by n table with m rows and n columns containing m X n
 elements.
 The no. of elements = no. of rows X no. of columns
 One of the use of 2-D numeric array is matrix manipulation which is one of the important concept
 of mathematics.



 Declaration of 2-D array:

 The general form of a two-dimensional array is
          Syntax:- Data-type array-name [rows] [columns];
 Where data-type is any base data type, array-name is any valid identifier name and rows, the
 first index indicates the no. of rows and columns the second index, indicates the no. of columns.
 For ex:- int Price [4] [5];
 The array Price have 4 elements Price[0], Price[1],……., Price[3] which itself an int array with 5
 elements. The individual elements of Price are referred to as Price[0][0], Price[0][1],…….,
 Price[0][3], Price[1][0], Price[1][1] and so forth. The last element will be Price [3][4].


 Memory Map Representation :-

 Ex:-                    int Price [4][5];

                                             Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 13

                                                    Columns
                                                                                     n-1
                           0         1          2              3        4
                 0

                 1
      Rows                                                                          m = rows, n = columns
                 2

                 3
                                                                                      Price [3][4]
                               Price [1] [1]
           m-1


  Size occupied by the above array in memory = data-type X rows X columns
                                          = 2 X 4 X 5 = 40 bytes
  C++ statement will be : cout << sizeof(Price);


  Array of Strings:- The two-dimensional character array is known as array of strings. The size of
  the first index (rows) is the number of strings and the size of the second index (columns) is the
  maximum length of each string.

  For ex:-       char days [7][11];
  Declares an array of 7 strings each of which can hold maximum of 10 valid characters where 1
  extra to take care of the null character ‘0’;




  The above array of strings appears in memory as shown below:
                                                        (11)
             0          1       2        3          4          5   6            7      8         9        10
       0     M         O       N         D          A      Y       0
       1     T         U       E         S          D      A       Y        0
       2     W         E       D         N          E      S       D        A         Y       0
(7)    3     T         H       U         R          S      D       A        Y         0
       4     F         R       I         D          A      Y       0
       5     S         A       T         U          R      D       A        Y         0
       6     S         U       N         D          A      Y       0

  Array Initialization:- Like One-dimensional array two-dimensional array can be initialized in two
  ways:-
            (i) Sized 2-D array initialization

                     int SQ[3][2] = { 1, 1,
                                      2, 4,
                                      3, 9
                                    };


                     int SQ[3][2] = {1,1, 2,4, 3,9};
                                               Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 13

              For Array of strings:
               Char Months[12][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”,
                                     “Aug”, “Sep”, “Oct”, “Nov”, “Dec”};

       (i) Unsized 2-D array initialization

              int Cube[ ][2] = { 1, 1,                    -- rows should be left blank
                                 2, 8,
                                 3, 27,
                                 4, 64
                                };

              Char Months[ ][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”,
                                      “Aug”, “Sep”, “Oct”, “Nov”, “Dec”};

       The advantage is that one can increase the rows as and when required.

        In C++ program nested loop is required for taking inputs for numeric type 2-D arrays
whereas generally single loop is used for taking inputs in character type 2-D arrays (i.e. for
array of strings).
For string input gets ( ) function (which is defined in stdio.h header file) is normally preferred
over cin>> operator since it can able to take the white space characters (tabs, spaces etc).

Code segment:              int Mat[4][5];
                           for (int i = 0; i < 4; i++)   {-- Nested loop
                             for (int j = 0; j < 5; j++)
                                cin >> Mat[i][j]; -- Here i indicates rows & j indicates
columns

                          char days [7][11];
                            for (int i = 0; i < 7; i++)
                              gets(days[i]);

//Q1. Write a program to display the multiplication of two matrices
#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int A[50][50],B[50][50],C[50][50];
 int r1,c1,r2,c2,i,j,k;
 cout<<"nEnter the rows & columns for matrix A:";
 cin>>r1>>c1;
 cout<<"nEnter the rows & columns for matrix B:";
 cin>>r2>>c2;
 cout<<"nEnter the elements for matrix A:n";
 for(i=0;i<r1;i++)
  for(j=0;j<c1;j++)
  {
   cout<<"element"<<i<<","<<j<<":";
   cin>>A[i][j];
  }
 cout<<"nEnter the elements for matrix B:n";
  for(i=0;i<r2;i++)
  for(j=0;j<c2;j++)
  {
   cout<<"element"<<i<<","<<j<<":";
   cin>>B[i][j];

                                      Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 13
  }
 if(c1!=r2)
 {
  cout<<"matrix multiplication is not possible!";
  getch();
  return;
 }
 else
 cout<<"multiplication is possible!";
 //Multiplication
 for(i=0;i<r1;i++)
 {
  for(j=0;j<c2;j++)
   {
    C[i][j]=0;
    for(k=0;k<r2;k++)
     {
      C[i][j]+=A[i][k]*B[k][j];
     }
   }
 }
cout<<"nMatrix A:n";
 for(i=0;i<r1;i++)
  {
   cout<<"n";
  for(j=0;j<c1;j++)
   cout<<A[i][j];
  }

cout<<"nMatrix B:n";
 for(i=0;i<r2;i++)
  {
   cout<<"n";
  for(j=0;j<c2;j++)
   cout<<B[i][j];
  }
cout<<"nProduct Matrix C:n";
 for(i=0;i<c1;i++)
  {
   cout<<"n";
  for(j=0;j<r2;j++)
   cout<<C[i][j];
 }
getch();
}


call by value & call by reference

A function can be invoked in two ways: call by value and call by reference

                  Call by value                                     Call by reference
In call by value method the values of actual        In call by reference a reference to the original
parameters (the parameters that appear in a         variable is passed. A reference is an alias (i.e.
function call statement i.e. the original values)   a different name) for a predefined variable.
are copied into the formal parameters (i.e.         This means the original values are referred
the parameters that appear in function              here. Here the called function does not creates
definition). Here the called function creates its   its own copy of original values, rather, it refers
own copy of argument values for the original        to the original values only by different names

                                       Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 13
values and uses them i.e. it works with the       i.e. the references i.e. it works with the original
duplicate data(s).                                data(s).

In this method if there is any change(s)          In this method if any change(s) occurred in the
occurred in the parameter(s), are not reflected   parameter(s), are reflected back to the original
back to the original values.                      values.

Example of call by value method:-
#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 void change(int); //prototype declaration
 int n;
 cout<<"n Enter any number:";
 cin>>n;
 cout<<"noriginal value="<<n<<endl;
 change(n); // function call
 cout<<"nValue after function call="<<n<<endl;
 getch();
 }

//function definition
void change(int n1)
{
 n1 = n1 + 5; //number is incremented by 5
 cout<<"nValue in function definition="<<n1;
}

Output:
Enter any number:5

original value=5

Value in function definition=10
Value after function call=5 // Here the changes are not reflected

Example of call by reference method:-

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 void change(int &); //prototype declaration (see the syntax)
 int n;
 cout<<"n Enter any number:";
 cin>>n;
 cout<<"noriginal value="<<n<<endl;
 change(n); // function call
 cout<<"nValue after function call="<<n<<endl;
 getch();
 }
 //function definition
 void change(int &n1)
 {
  n1 = n1 + 5; //number is incremented by 5
  cout<<"nValue in function definition="<<n1;

                                      Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 7 of 13
}


Output:

Enter any number:5

original value=5

Value in function definition=10
Value after function call=10    //Here the changes are reflected

Note:   The parameters are also known as arguments.

Reference Variables:- Reference variables are the variables which refer to other variables by a
different name. If we want to create another name of any variable then we have to use reference
variables;
For ex:-      int a =10;
              int &b = a;                        10               0x8fc9fff4

Both refer to the same memory area
Where 10 is stored.                          a                  b


Passing arrays to functions (numeric & string)

Numeric array and string array can be passed as an argument to functions. Whenever we want to
pass a numeric array as an argument to functions we have to provide the array name (Since it
is pointer to its base address i.e. holds the starting address of the array) along with its size.
But in case of character array (i.e. for strings) we need to provide only the array name. This
is because the string is terminated by null character in C++ so the size of the string is
automatically understandable by the compiler.

Let us take examples to illustrate this:

Q To display the highest & lowest marks of 10 students in a particular subject using
array as an argument to a function

#include<iostream.h>
#include<conio.h>
void main()
{
void ArrHL(int [ ],int); // prototype declaration
int A[10],i;
cout<<"nEnter the subject marks:n";
 for(i=0;i<10;i++)
  {
  cout<<"marks "<<i+1<<":";
  cin>>A[i];
  }
 ArrHL(A,i); //function call
getch();
}
void ArrHL(int A1[],int n) //arguments are int array A and its size
{
                                       // [ ] indicates it can any size
 int H,L;

for(int i=0;i<n;i++)

                                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 8 of 13
 {
  L=A1[0];
  H=A1[0];
 if(A1[i]>H)
  H=A1[i];
 if(A1[i]<L)
  L=A1[i];
 }
 cout<<"nHighest Number="<<H<<endl;
 cout<<"nLowest Number="<<L;
}
output
Enter the subject marks:
marks 1:2
marks 2:6
marks 3:8
marks 4:121
marks 5:17
marks 6:19
marks 7:0
marks 8:23
marks 9:25
marks 10:29

Highest Number=29

Lowest Number=2

Q. To find the reverse of a string and its length by passing a character array in a
function.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int strlencount(char []); // prototype declaration
char str[31];
cout<<"nEnter the string:";
gets(str);
cout<<"nString Length= "<<strlencount(str); //function call
getch();
}
int strlencount(char str1[]) //argument is char array
{
 int len=0,i;
 for(i=0; str1[i]!='0'; i++)
  len++;
 for(i=len-1;i>=0;i--)
 cout<<str1[i];        //We can also write cout<<str;
return len;
}

Note: - Similarly 2-D array can also be passed as an argument to an array.


                                    Library Functions


                                   Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 9 of 13
Library is a collection of subprograms used to develop other programs and software.
The C++ library of functions stores functions of same category e.g. mathematical
functions, string functions, character functions etc. under separate files known as
header files.
Header files provide function prototypes, definitions for library functions.

Mathematical functions Header File (math.h)

SL.   Function     Prototype (General        Description                           Example
NO.                Form)
1     exp          double   exp(double       The exp( ) function returns the       exp(2.0)      gives
                   arg)                      natural logarithm e raised to the     the value e2.
                                             arg power.
2     pow          double pow(double         The pow( ) function returns arg1      pow(3,2)     gives
                   arg1, double arg2)        raised to arg2 power i.e. arg1 arg2   9.
                                             . A domain error occur if arg1        pow(3.0,0) gives
                                             = 0 and arg2 <= 0. Also if            1.
                                             arg1 < 0 and arg2 is not an           pow(4.0,2.0)
                                             integer.                              gives 16.
3     sqrt         double sqrt (double       The sqrt( ) function returns the      sqrt(9) gives 3
                   num)                      square root of num. if num < 0        sqrt(81.0) gives
                                             domain error occurs.                  9.0
4     fabs         double fabs (double       The fabs ( ) function returns the     fabs(2.0)    gives
                   num)                      absolute value of num.                2.0.
                                                                                   fabs(-3) gives 3.
5     log 10       double log10(double       The log10( ) function returns the     log 10(1.0) gives
                   num)                      base 10 logarithm for num. A          base            10
                                             domain error occurs if num is         logarithm for 1.0
                                             negative and a range error is
                                             occurs if the argument num is
                                             zero.
6     log          double log(double         The log( ) function returns the       log (1.0) gives
                   num)                      natural logarithm for num. A          natural logarithm
                                             domain error occurs if num is         for 1.0
                                             negative and a range error is
                                             occurs if the argument num is
                                             zero.
7     fmod         double fmod(double x,     The fmod( ) function returns          fmod(10.0,4.0)
                   double y)                 reamainder of the division x/y.       returns 2.0

Note:- abs ( ) function is used to find the absolute value for integer numbers and mod(
) function is used to find the remainder when one integer is divided by another integer
number.



String functions      Header file string.h

SL.   Function                    Description                       Example
NO.
1     strcpy(s1,s2)               This function copies character    strcpy(“Vidyalaya”,
                                  string s2 to string s1. The s1    “Kendriya”) will give Kendriya.
                                  must have enough reserved
                                  elements to hold the string
                                  s2.
2     strcat(s1,s2)               This function concatenates        strcat(“Computer”,”Science”)
                                  (merges) two strings. The         will give ComputerScience.
                                  string s2 will be added at the
                                  end of string s1. The array s1
                                       Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 10 of 13
                                    must have enough reserved
                                    elements to hold the string
                                    s2.
3      strcmp(s1,s2)                This function compares the         Strcmp(“KVS”,”KBS”);
                                    strings s1 with s2 on an           It will return -1
                                    alphabetic       element      by
                                    element basis.If s1>s2 then
                                    it return 1 if s1=s2 it return 0
                                    And if s1<s2 it return -1


      Character functions

Header File - ctype.h

Function                     Description                               Example
int isalnum(int,c)   This functions returns nonzero value if its       char c=’A’
                     Argument c is a letter or digit, if the           if (isalnum( c))
                     character is not an alphanumeric then it          cout<<”Alphanum”;
                     returns zero.
int isalpha(int,c)   This functions returns nonzero value if its       if (isalpha( c))
                     Argument c is a alphabet if the character is      cout<<”Alphabet”;
                     not an alphanumeric then it returns zero.
int isalnum(int,c)   This functions returns nonzero value if its       if (isdigit( c))
                     Argument c is a digit, if the c is not digit      cout<<”Digit”;
                     then it returns zero.
int islower(int,c)   This functions returns nonzero value if its       if (islower( c))
                     Argument c is in lowercase letter, otherwise      cout<<”Lower
                     it returns zero.                                  case”;
int isupper(c)       This functions returns nonzero value if its       if (isupper( c))
                     Argument c is in uppercase letter, otherwise      cout<<”Upper
                     it returns zero.                                  case”;
int toupper(int,c)   This functions returns uppercase equivalent       Char c=’a’
                     of c if c is already in upper case it remains     cout<<toupper(c);
                     unchange.                                         output A
int tolower(int,c)   This functions returns lowercase equivalent       Char c=’A’
                     of c if c is already in lower case case it        cout<<tolower(c);
                     remains unchanged.                                output a
Questions
Array

1.Write a program in C++ to interchange the values of the row and column.

2 Write a user define function xyz() which takes a two dimensional array with size N rows and N
columnsas argument and store all 1)even in one dimensional array2) All odd in one dimensional
array 3. display product of all the number except those which are not divisible by either 5 or 3.
4. write a user define function unitdigit() which takes a two dimensional array with size N rows
and M columns as argument and store all i) unit digit ii) except unit digit
In two dimensional array. i.e
        A[2][3] = 200                213
                  56          657
        Resultant array should be
        i)     A[2][3] =      0              3
                              6              7
        ii)    A[2][3] =      20             21
                              5              65
5. Write a user define function repeat() which takes a two dimensional array with size N rows
and M columns as argument and convert all repeated element into zero.


                                       Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 11 of 13
6. Write a user define function convert() which takes a one dimensional array with size N as
argument and convert it into two dimensional array.
Suppose arr[6]= { 1,2,3,4,5,6}
 Resultant array should be
       Arr[6][6] = 2           1 4 36 5
                    2 1 4 36 0
                    2 1 4 30 0
                    2 1 4 00 0
                    2 1 000 0
                    2 0 0 00 0

                               Write a function in C++ to replace the repeating elements in an
                                array by 0 . The zeros should be shifted to the end. Do not use
                                parallel array . The order of the array should not change.    (2)

              Eg : Array       : 10 , 20 , 30 , 10 , 40 , 20 , 30

              Result : 10 , 20 , 30 , 40 , 0 , 0 , 0

7. Write a function in C++ called shift( ) to rearrange the matrix as shown . Do not use parallel
matrix .                                                         (2)

              Original Matrix                                Rearranged Matrix

              1      2         -3     -2               -3    -2     1     2
              0      -1        2      1                -1    0      2     1
              -3     9         -4     4                -3    -4     9     4



8. Find the output of the following program:
#include <iostream.h>
void modify(int arr[ ], int N)
{
for (int I=1;I<N;I++)
    arr[ I-1]+=arr[ I ];
}
void main()
{
int P[]={1,2,3,4},Q[]={5,10,15,20,30};
modify(P,4);
modify(Q,5);
for (int L=0;L<4;L++)
       cout<<P[L]<<”$”;
cout<<endl;
for (L=0;L<5;L++)
       cout<<Q[L] <<”$”;
cout<<endl;
}




9. Find the output of the following program:
#include <iostream.h>
int a=5;

                                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 12 of 13
void sample( int &x, int y , int *z)
   {
    a+=x;
    y*=a;
    *z=a+y;
    cout<<a<<” “ <<x<<” “<< y<<” “<<*z<<”n”;
    }
 void main()
     {
       clrscr();
       int a =7 ,int b = 5 ;
       sample(::a , a , &b);
       cout<< ::a << “ “ << a <<” “<<b <<”n”;
       sample(::a , a , &b);
       cout<< ::a << “ “ << a <<” “<<b <<”n”;
      }

10. Write a function in C++ to add new objects at the bottom of a binary file “TICKET.DAT”,
assuming the binary file is containing the objects of the following class.



class LOTTERY
{
int LotTicNo;
char StateCode[5];
public:
void Enter(){cin>>LotTicNo;gets(StateCode);}
void Display(){cout<<LotTicNo<<StateCode<<endl;}
};


11.     Write a function in C++ that will read the contents of a file
        EXAM.DAT and display the details of those students whose marks>75.
        The binary file EXAM.DAT containing records of student.       2
               class student
               {       char roll [4];
                       char name[20];
                       int marks;
                       public :
                       void Read_Data ( ) ;
                       // Entering data in to the file
                       void Show_Date ( );
                       //Displaying the content of the file


12 . Find the output of the following program. Assume that all required headers files have been
      included.                                   2
                  int funs (int &x, int y=10)
                  {       if (x%y == 10)
                                 return ++x;
                          else
                                 return y-- ;
                  }
                  void main( )
                  {       int p=20, q=23;
                          q = funs(p,q);
                          cout <<p<<”;”<<q<< endl;
                          q = funs(p);

                                       Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 13 of 13
    cout <<p<<”;”<<q<<endl;
}




                 Prepared By Sumit Kumar Gupta, PGT Computer Science

More Related Content

What's hot

What's hot (20)

Lecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional ArrayLecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional Array
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Array in c++
Array in c++Array in c++
Array in c++
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Array and string
Array and stringArray and string
Array and string
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
Array in c
Array in cArray in c
Array in c
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Array
ArrayArray
Array
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Lecture17 arrays.ppt
Lecture17 arrays.pptLecture17 arrays.ppt
Lecture17 arrays.ppt
 
2D Array
2D Array 2D Array
2D Array
 

Viewers also liked (10)

Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Class
ClassClass
Class
 
Physics
PhysicsPhysics
Physics
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
Boolean algebra laws
Boolean algebra lawsBoolean algebra laws
Boolean algebra laws
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 

Similar to Arrays and library functions

Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT LATHA LAKSHMI
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysMaulen Bale
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programmingnmahi96
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptxFolkAdonis
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxrohinitalekar1
 

Similar to Arrays and library functions (20)

Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
Arrays
ArraysArrays
Arrays
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Structured Data Type Arrays
Structured Data Type ArraysStructured Data Type Arrays
Structured Data Type Arrays
 
2ds
2ds2ds
2ds
 
Unit 2
Unit 2Unit 2
Unit 2
 
Arrays
ArraysArrays
Arrays
 

More from Swarup Kumar Boro (16)

c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
Pointers
PointersPointers
Pointers
 
File handling
File handlingFile handling
File handling
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Queue
QueueQueue
Queue
 
Stack
StackStack
Stack
 
Functions
FunctionsFunctions
Functions
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
2-D array
2-D array2-D array
2-D array
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Unit 3
Unit  3Unit  3
Unit 3
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
1-D array
1-D array1-D array
1-D array
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Physics activity
Physics activityPhysics activity
Physics activity
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

Arrays and library functions

  • 1. Page 1 of 13 Arrays and Library Functions Arrays: - An array is a collection of variables of the same type that are referenced by a common name. It consists of contiguous memory locations. Need for arrays:- For large applications or calculations say to find the average marks of 50 students if we use 50 different variables the job will be cumbersome and tedious and program maintenance will be very difficult. But if we use array the remembering and managing these variables will be easy. To make the program complex –free and more understandable array is used. Declaration of arrays: Syntax:- data-type array-name[size]; For ex:- int A[10]; float B[20]; char C[30]; where data-type refers to any fundamental(or primitive or in-built) data types, array-name will be any valid identifier name and size will be any number which indicates no. of elements the array contains. Types of Arrays:- Arrays are of two types:- (i) one-dimensional arrays and (ii) Two- dimensional arrays. Both the arrays can be of numeric as well as character (or string) types. (i) One-dimensional (or single dimensional or 1-D) arrays:- It is a collection of similar types of elements referenced by a common name. The elements of the are referred by their subscripts or indices. For eg. int A[5]; The above array will be having elements : A[0], A[1], A[2], A[4], A[5]. Array subscripts ( the numbers which are within [ ] ) always starts with number 0 not 1 in C++. Subscripts are the locations of the elements within the array. Memory representation of 1-D array Let us take the above example which is int A[5]; A[0] A[1] A[2] A[3] A[4] Location Starting 25 -13 44 0 10 address value Where A[0] is the first element, A[1] is the second element and so on. The last element (i.e. 10 here) always having location A[size-1]. Each element contains 2 bytes of memory. The address of first element of the array i.e. &A[0] is called the base address of the array. Note:- The name of the array (here A) is a pointer to its base address i.e. first element’s address (i.e. &A[0]). Size of the array in memory = data-type X size of the array For the above array the memory occupied will be 2 X 5 = 10 bytes. We can find it using C++ coding also cout << sizeof(A); here sizeof is a operator which is used to find the size of any data type, variable or derived data type in bytes and A is the array name. Initialization of One-dimensional array (Numeric type):- There are two types of initialization (i) Sized array initialization and (ii) unsized array initialization (i) Sized array initialization :- It can be done during the program writing (i.e. before program execution) or during the program execution (Using Loop). For ex:- int A[5] = {12, 13, 20, 5, 2}; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 13 float B[4] = { 3.4, 4.5, 6.2, 7.8}; This is sometimes called direct initialization. code segment: int A[5]; for( int i=0; i<5; i++) cin >> A[i]; Here the values must be provided by the user during the execution of the program. In the first case the values are actually assigned during the compilation time and in the second case the values are assigned during the execution time by the user’s input. (i) Unsized array initialization :- It can only be done in following ways: int A[ ] = {2, 5, 17, 10, 12}; // No size is given within [ ] char str[ ] = “Kendriya Vidyalaya”; The compiler will automatically fixed the size of the array. Here the advantage is that the number of elements can be increased or decreased without considering the size. It is more flexible whenever there is a requirement of direct initialization or the values are known to the user. String as an array:- C++ does not string data types rather it implements string as one- dimensional character arrays. String is defined as a array of characters that is terminated by a null character ‘0’. For ex:- char str[20] = “Kendriya Vidyalaya”; It can be represented as Location in the array str[0] str[8] str[18] K e n d r i y a V i d y a l a y a 0 The above array contains 18 characters , but it can contain maximum of 19 characters i.e. size – 1 characters and one space is reserved for null character. Here the length of the array is 18. The position of null character is not taken for finding the length of the array. (i) Two-dimensional (2-D) arrays:- A two-dimensional array is a multi one-dimensional arrays. It consists of rows and columns i.e. it is in a matrix format. For instance an array A[m][n] is an m by n table with m rows and n columns containing m X n elements. The no. of elements = no. of rows X no. of columns One of the use of 2-D numeric array is matrix manipulation which is one of the important concept of mathematics. Declaration of 2-D array: The general form of a two-dimensional array is Syntax:- Data-type array-name [rows] [columns]; Where data-type is any base data type, array-name is any valid identifier name and rows, the first index indicates the no. of rows and columns the second index, indicates the no. of columns. For ex:- int Price [4] [5]; The array Price have 4 elements Price[0], Price[1],……., Price[3] which itself an int array with 5 elements. The individual elements of Price are referred to as Price[0][0], Price[0][1],……., Price[0][3], Price[1][0], Price[1][1] and so forth. The last element will be Price [3][4]. Memory Map Representation :- Ex:- int Price [4][5]; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 13 Columns n-1 0 1 2 3 4 0 1 Rows m = rows, n = columns 2 3 Price [3][4] Price [1] [1] m-1 Size occupied by the above array in memory = data-type X rows X columns = 2 X 4 X 5 = 40 bytes C++ statement will be : cout << sizeof(Price); Array of Strings:- The two-dimensional character array is known as array of strings. The size of the first index (rows) is the number of strings and the size of the second index (columns) is the maximum length of each string. For ex:- char days [7][11]; Declares an array of 7 strings each of which can hold maximum of 10 valid characters where 1 extra to take care of the null character ‘0’; The above array of strings appears in memory as shown below: (11) 0 1 2 3 4 5 6 7 8 9 10 0 M O N D A Y 0 1 T U E S D A Y 0 2 W E D N E S D A Y 0 (7) 3 T H U R S D A Y 0 4 F R I D A Y 0 5 S A T U R D A Y 0 6 S U N D A Y 0 Array Initialization:- Like One-dimensional array two-dimensional array can be initialized in two ways:- (i) Sized 2-D array initialization int SQ[3][2] = { 1, 1, 2, 4, 3, 9 }; int SQ[3][2] = {1,1, 2,4, 3,9}; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 13 For Array of strings: Char Months[12][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}; (i) Unsized 2-D array initialization int Cube[ ][2] = { 1, 1, -- rows should be left blank 2, 8, 3, 27, 4, 64 }; Char Months[ ][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}; The advantage is that one can increase the rows as and when required. In C++ program nested loop is required for taking inputs for numeric type 2-D arrays whereas generally single loop is used for taking inputs in character type 2-D arrays (i.e. for array of strings). For string input gets ( ) function (which is defined in stdio.h header file) is normally preferred over cin>> operator since it can able to take the white space characters (tabs, spaces etc). Code segment: int Mat[4][5]; for (int i = 0; i < 4; i++) {-- Nested loop for (int j = 0; j < 5; j++) cin >> Mat[i][j]; -- Here i indicates rows & j indicates columns char days [7][11]; for (int i = 0; i < 7; i++) gets(days[i]); //Q1. Write a program to display the multiplication of two matrices #include<iostream.h> #include<conio.h> void main() { clrscr(); int A[50][50],B[50][50],C[50][50]; int r1,c1,r2,c2,i,j,k; cout<<"nEnter the rows & columns for matrix A:"; cin>>r1>>c1; cout<<"nEnter the rows & columns for matrix B:"; cin>>r2>>c2; cout<<"nEnter the elements for matrix A:n"; for(i=0;i<r1;i++) for(j=0;j<c1;j++) { cout<<"element"<<i<<","<<j<<":"; cin>>A[i][j]; } cout<<"nEnter the elements for matrix B:n"; for(i=0;i<r2;i++) for(j=0;j<c2;j++) { cout<<"element"<<i<<","<<j<<":"; cin>>B[i][j]; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 13 } if(c1!=r2) { cout<<"matrix multiplication is not possible!"; getch(); return; } else cout<<"multiplication is possible!"; //Multiplication for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { C[i][j]=0; for(k=0;k<r2;k++) { C[i][j]+=A[i][k]*B[k][j]; } } } cout<<"nMatrix A:n"; for(i=0;i<r1;i++) { cout<<"n"; for(j=0;j<c1;j++) cout<<A[i][j]; } cout<<"nMatrix B:n"; for(i=0;i<r2;i++) { cout<<"n"; for(j=0;j<c2;j++) cout<<B[i][j]; } cout<<"nProduct Matrix C:n"; for(i=0;i<c1;i++) { cout<<"n"; for(j=0;j<r2;j++) cout<<C[i][j]; } getch(); } call by value & call by reference A function can be invoked in two ways: call by value and call by reference Call by value Call by reference In call by value method the values of actual In call by reference a reference to the original parameters (the parameters that appear in a variable is passed. A reference is an alias (i.e. function call statement i.e. the original values) a different name) for a predefined variable. are copied into the formal parameters (i.e. This means the original values are referred the parameters that appear in function here. Here the called function does not creates definition). Here the called function creates its its own copy of original values, rather, it refers own copy of argument values for the original to the original values only by different names Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 13 values and uses them i.e. it works with the i.e. the references i.e. it works with the original duplicate data(s). data(s). In this method if there is any change(s) In this method if any change(s) occurred in the occurred in the parameter(s), are not reflected parameter(s), are reflected back to the original back to the original values. values. Example of call by value method:- #include<iostream.h> #include<conio.h> void main() { clrscr(); void change(int); //prototype declaration int n; cout<<"n Enter any number:"; cin>>n; cout<<"noriginal value="<<n<<endl; change(n); // function call cout<<"nValue after function call="<<n<<endl; getch(); } //function definition void change(int n1) { n1 = n1 + 5; //number is incremented by 5 cout<<"nValue in function definition="<<n1; } Output: Enter any number:5 original value=5 Value in function definition=10 Value after function call=5 // Here the changes are not reflected Example of call by reference method:- #include<iostream.h> #include<conio.h> void main() { clrscr(); void change(int &); //prototype declaration (see the syntax) int n; cout<<"n Enter any number:"; cin>>n; cout<<"noriginal value="<<n<<endl; change(n); // function call cout<<"nValue after function call="<<n<<endl; getch(); } //function definition void change(int &n1) { n1 = n1 + 5; //number is incremented by 5 cout<<"nValue in function definition="<<n1; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 7. Page 7 of 13 } Output: Enter any number:5 original value=5 Value in function definition=10 Value after function call=10 //Here the changes are reflected Note: The parameters are also known as arguments. Reference Variables:- Reference variables are the variables which refer to other variables by a different name. If we want to create another name of any variable then we have to use reference variables; For ex:- int a =10; int &b = a; 10 0x8fc9fff4 Both refer to the same memory area Where 10 is stored. a b Passing arrays to functions (numeric & string) Numeric array and string array can be passed as an argument to functions. Whenever we want to pass a numeric array as an argument to functions we have to provide the array name (Since it is pointer to its base address i.e. holds the starting address of the array) along with its size. But in case of character array (i.e. for strings) we need to provide only the array name. This is because the string is terminated by null character in C++ so the size of the string is automatically understandable by the compiler. Let us take examples to illustrate this: Q To display the highest & lowest marks of 10 students in a particular subject using array as an argument to a function #include<iostream.h> #include<conio.h> void main() { void ArrHL(int [ ],int); // prototype declaration int A[10],i; cout<<"nEnter the subject marks:n"; for(i=0;i<10;i++) { cout<<"marks "<<i+1<<":"; cin>>A[i]; } ArrHL(A,i); //function call getch(); } void ArrHL(int A1[],int n) //arguments are int array A and its size { // [ ] indicates it can any size int H,L; for(int i=0;i<n;i++) Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 8. Page 8 of 13 { L=A1[0]; H=A1[0]; if(A1[i]>H) H=A1[i]; if(A1[i]<L) L=A1[i]; } cout<<"nHighest Number="<<H<<endl; cout<<"nLowest Number="<<L; } output Enter the subject marks: marks 1:2 marks 2:6 marks 3:8 marks 4:121 marks 5:17 marks 6:19 marks 7:0 marks 8:23 marks 9:25 marks 10:29 Highest Number=29 Lowest Number=2 Q. To find the reverse of a string and its length by passing a character array in a function. #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { clrscr(); int strlencount(char []); // prototype declaration char str[31]; cout<<"nEnter the string:"; gets(str); cout<<"nString Length= "<<strlencount(str); //function call getch(); } int strlencount(char str1[]) //argument is char array { int len=0,i; for(i=0; str1[i]!='0'; i++) len++; for(i=len-1;i>=0;i--) cout<<str1[i]; //We can also write cout<<str; return len; } Note: - Similarly 2-D array can also be passed as an argument to an array. Library Functions Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 9. Page 9 of 13 Library is a collection of subprograms used to develop other programs and software. The C++ library of functions stores functions of same category e.g. mathematical functions, string functions, character functions etc. under separate files known as header files. Header files provide function prototypes, definitions for library functions. Mathematical functions Header File (math.h) SL. Function Prototype (General Description Example NO. Form) 1 exp double exp(double The exp( ) function returns the exp(2.0) gives arg) natural logarithm e raised to the the value e2. arg power. 2 pow double pow(double The pow( ) function returns arg1 pow(3,2) gives arg1, double arg2) raised to arg2 power i.e. arg1 arg2 9. . A domain error occur if arg1 pow(3.0,0) gives = 0 and arg2 <= 0. Also if 1. arg1 < 0 and arg2 is not an pow(4.0,2.0) integer. gives 16. 3 sqrt double sqrt (double The sqrt( ) function returns the sqrt(9) gives 3 num) square root of num. if num < 0 sqrt(81.0) gives domain error occurs. 9.0 4 fabs double fabs (double The fabs ( ) function returns the fabs(2.0) gives num) absolute value of num. 2.0. fabs(-3) gives 3. 5 log 10 double log10(double The log10( ) function returns the log 10(1.0) gives num) base 10 logarithm for num. A base 10 domain error occurs if num is logarithm for 1.0 negative and a range error is occurs if the argument num is zero. 6 log double log(double The log( ) function returns the log (1.0) gives num) natural logarithm for num. A natural logarithm domain error occurs if num is for 1.0 negative and a range error is occurs if the argument num is zero. 7 fmod double fmod(double x, The fmod( ) function returns fmod(10.0,4.0) double y) reamainder of the division x/y. returns 2.0 Note:- abs ( ) function is used to find the absolute value for integer numbers and mod( ) function is used to find the remainder when one integer is divided by another integer number. String functions Header file string.h SL. Function Description Example NO. 1 strcpy(s1,s2) This function copies character strcpy(“Vidyalaya”, string s2 to string s1. The s1 “Kendriya”) will give Kendriya. must have enough reserved elements to hold the string s2. 2 strcat(s1,s2) This function concatenates strcat(“Computer”,”Science”) (merges) two strings. The will give ComputerScience. string s2 will be added at the end of string s1. The array s1 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 10. Page 10 of 13 must have enough reserved elements to hold the string s2. 3 strcmp(s1,s2) This function compares the Strcmp(“KVS”,”KBS”); strings s1 with s2 on an It will return -1 alphabetic element by element basis.If s1>s2 then it return 1 if s1=s2 it return 0 And if s1<s2 it return -1 Character functions Header File - ctype.h Function Description Example int isalnum(int,c) This functions returns nonzero value if its char c=’A’ Argument c is a letter or digit, if the if (isalnum( c)) character is not an alphanumeric then it cout<<”Alphanum”; returns zero. int isalpha(int,c) This functions returns nonzero value if its if (isalpha( c)) Argument c is a alphabet if the character is cout<<”Alphabet”; not an alphanumeric then it returns zero. int isalnum(int,c) This functions returns nonzero value if its if (isdigit( c)) Argument c is a digit, if the c is not digit cout<<”Digit”; then it returns zero. int islower(int,c) This functions returns nonzero value if its if (islower( c)) Argument c is in lowercase letter, otherwise cout<<”Lower it returns zero. case”; int isupper(c) This functions returns nonzero value if its if (isupper( c)) Argument c is in uppercase letter, otherwise cout<<”Upper it returns zero. case”; int toupper(int,c) This functions returns uppercase equivalent Char c=’a’ of c if c is already in upper case it remains cout<<toupper(c); unchange. output A int tolower(int,c) This functions returns lowercase equivalent Char c=’A’ of c if c is already in lower case case it cout<<tolower(c); remains unchanged. output a Questions Array 1.Write a program in C++ to interchange the values of the row and column. 2 Write a user define function xyz() which takes a two dimensional array with size N rows and N columnsas argument and store all 1)even in one dimensional array2) All odd in one dimensional array 3. display product of all the number except those which are not divisible by either 5 or 3. 4. write a user define function unitdigit() which takes a two dimensional array with size N rows and M columns as argument and store all i) unit digit ii) except unit digit In two dimensional array. i.e A[2][3] = 200 213 56 657 Resultant array should be i) A[2][3] = 0 3 6 7 ii) A[2][3] = 20 21 5 65 5. Write a user define function repeat() which takes a two dimensional array with size N rows and M columns as argument and convert all repeated element into zero. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 11. Page 11 of 13 6. Write a user define function convert() which takes a one dimensional array with size N as argument and convert it into two dimensional array. Suppose arr[6]= { 1,2,3,4,5,6} Resultant array should be Arr[6][6] = 2 1 4 36 5 2 1 4 36 0 2 1 4 30 0 2 1 4 00 0 2 1 000 0 2 0 0 00 0  Write a function in C++ to replace the repeating elements in an array by 0 . The zeros should be shifted to the end. Do not use parallel array . The order of the array should not change. (2) Eg : Array : 10 , 20 , 30 , 10 , 40 , 20 , 30 Result : 10 , 20 , 30 , 40 , 0 , 0 , 0 7. Write a function in C++ called shift( ) to rearrange the matrix as shown . Do not use parallel matrix . (2) Original Matrix Rearranged Matrix 1 2 -3 -2 -3 -2 1 2 0 -1 2 1 -1 0 2 1 -3 9 -4 4 -3 -4 9 4 8. Find the output of the following program: #include <iostream.h> void modify(int arr[ ], int N) { for (int I=1;I<N;I++) arr[ I-1]+=arr[ I ]; } void main() { int P[]={1,2,3,4},Q[]={5,10,15,20,30}; modify(P,4); modify(Q,5); for (int L=0;L<4;L++) cout<<P[L]<<”$”; cout<<endl; for (L=0;L<5;L++) cout<<Q[L] <<”$”; cout<<endl; } 9. Find the output of the following program: #include <iostream.h> int a=5; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 12. Page 12 of 13 void sample( int &x, int y , int *z) { a+=x; y*=a; *z=a+y; cout<<a<<” “ <<x<<” “<< y<<” “<<*z<<”n”; } void main() { clrscr(); int a =7 ,int b = 5 ; sample(::a , a , &b); cout<< ::a << “ “ << a <<” “<<b <<”n”; sample(::a , a , &b); cout<< ::a << “ “ << a <<” “<<b <<”n”; } 10. Write a function in C++ to add new objects at the bottom of a binary file “TICKET.DAT”, assuming the binary file is containing the objects of the following class. class LOTTERY { int LotTicNo; char StateCode[5]; public: void Enter(){cin>>LotTicNo;gets(StateCode);} void Display(){cout<<LotTicNo<<StateCode<<endl;} }; 11. Write a function in C++ that will read the contents of a file EXAM.DAT and display the details of those students whose marks>75. The binary file EXAM.DAT containing records of student. 2 class student { char roll [4]; char name[20]; int marks; public : void Read_Data ( ) ; // Entering data in to the file void Show_Date ( ); //Displaying the content of the file 12 . Find the output of the following program. Assume that all required headers files have been included. 2 int funs (int &x, int y=10) { if (x%y == 10) return ++x; else return y-- ; } void main( ) { int p=20, q=23; q = funs(p,q); cout <<p<<”;”<<q<< endl; q = funs(p); Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 13. Page 13 of 13 cout <<p<<”;”<<q<<endl; } Prepared By Sumit Kumar Gupta, PGT Computer Science