Passing array to a function cpp code

Leave a Comment
 This Cpp Tutorial contains
  • 3 ways to pass an array to a function
  • Each way and its usage
  • 3 c++ codes examples
  • How codes are working 
  • Sample output
  • Compiler used "C++ CodeBlocks Compiler"

Write a program which declares an array, initialize it then pass to a function. Function takes square of array values and update it. Show updated values in main function.

Concept used:
How programs works
  •   Declare array of size 10
  •   Initialize it using for loop
  •   Calling "UpdateArray" function and passing array as           argument
  •   Take squares of all values and update it
  •   Display final result in main function
 
Note: Function return type is void why? 
          As we know array name is constant pointer memory location if we get this location we can update it after updating if we access this memory location any where in the program we will get updated values. So no necessarily needs to return array or pointer.

First way
As we know array name is a constant pointer if we can get the this pointer we can access all values of array.
declaring  array in function parameter
Prototype: void  UpdateArray(int array[] );

 c++ code

  1.  #include <iostream>
  2.  using namespace std;
  3.  void UpdateArray(int array[])
  4.  {
  5.      for(int i=0;i<=9;i++)
  6.           array[i]=array[i]*array[i];
  7.  }
  8.  int main()
  9.  {
  10.      int array[10];
  11.      for(int i=0;i<=9;i++)
  12.           array[i]=i+1;
  13.      UpdateArray(array);
  14.  // Updated Values of Array
  15.      for(int i=0;i<=9;i++)
  16.           cout<<array[i]<<endl;
  17.      return 0;
  18.  }


Second way
Prototype: void  UpdateArray(int *array );
Declaring an integer pointer in function parameter
This pointer will receive arrays name(constant pointer) and we can access all values and update too.

  1.   #include <iostream>
  2.  using namespace std;
  3.  void UpdateArray(int *array)
  4.  {
  5.      for(int i=0;i<=9;i++)
  6.           array[i]=array[i]*array[i];
  7.  }
  8.  int main()
  9.  {
  10.      int array[10];
  11.      for(int i=0;i<=9;i++)
  12.           array[i]=i+1;
  13.      UpdateArray(array);
  14.  // Updated Values of Array
  15.      for(int i=0;i<=9;i++)
  16.           cout<<array[i]<<endl;
  17.      return 0;
  18. }


Third way
 In this way we pass two arguments one is arrays name and second   is its size
 In function receiving parameters we declares an array or integer pointer (your choice) to receive address of array and another integer variable size which contains the size of array.
Prototype:  void  UpdateArray(int *array, int size );

  1.  #include <iostream>
  2.  using namespace std;
  3.  void UpdateArray(int *array, int size)
  4.  {
  5.      for(int i=0;i<size;i++)
  6.           array[i]=array[i]*array[i];
  7.  }
  8.  int main()
  9.  {
  10.      int array[10];
  11.      for(int i=0;i<=9;i++)
  12.           array[i]=i+1;
  13.      UpdateArray(array,10);
  14.  // Updated Values of Array
  15.      for(int i=0;i<=9;i++)
  16.           cout<<array[i]<<endl;
  17.      return 0;
  18.  }
 Sample output all the codes have same
passing array to a function cpp code different ways
more Arrays Examples Here
C++ Simple Examples
For best practice do experiment with codes and examine output

if any confusion found dry run the code on a paper.
Read More...

Matrices Multiplication in C++ Code Tutorial

Leave a Comment
Write a simple c++ program to multiply two matrices using 2D arrays. Use any compiler turbo c, visual studio or codeblocks compiler.

Program Explanation:

  • Here is the simple example for beginners to understand the basic working of 2Dimensional arrays.
  • Program is very simple it takes input in two 2D arrays each with size of 2X2. 
  • After taking the input program multiply two matrix in 3 nested for loops.
  • Size of arrays is defined using "const int variables" Note: if we do not use const here there will be error because array size needs constant value in square brackets e.g.  array[const value]
Program code:
Compiler used: CodeBlocks C++ Compiler

#include<iostream>
using namespace std;
int main(){
//Using const int for array size
    const int row=2,col=2;
// if not use const error found
cout<<"Size of Matrices : "<<row<<" X "<<col<<endl;
cout<<"Enter Value For FirstMatrix Matrix:"<<endl;

    int firstMatrix[row][col];
    int secondMatrix[row][col];
    int resultantMatrix[row][col], var;

int i,j;
    for( i=0;i<row;i++){
        cout<<"Enter value for row number: "<<i+1<<endl;
        for( j=0;j<col;j++){
            cin>>firstMatrix[i][j];
        }
    }
cout<<"\n\n\nEnter Value For SecondMatrix Matrix:"<<endl;
    for( i=0;i<row;i++){
        cout<<"Enter value for row number: "<<i+1<<endl;
        for( j=0;j<col;j++){
            cin>>secondMatrix[i][j];
        }
    }
var=0;
        // ResultantMatrixant Matrix
        for( i=0;i<row;i++){
            for( j=0;j<col;j++){
                for(int k=0;k<row;k++){
                   var=var+(firstMatrix[i][k]*secondMatrix[k][j]);
                   cout<<var<<endl;
                    }
                 resultantMatrix[i][j]=var;
                 var=0;
            }
        }
cout<<"\n\n\t\tResultant Matrix:"<<endl;

    for( i=0;i<row;i++){
        cout<< endl;
        for( j=0;j<col;j++){
            cout<<"\t\t"<<resultantMatrix[i][j]<<"    ";
        }
    }
return 0;
}






Example input/output
c++ program to calculate matrix multiplication using 2D arrays
This program is very helpful for beginners it can be a complex by adding a matrix multiplication rule.
It is recommended to run this code and add the condition where number of colums of first matrix should be equal than the number of rows of second matrix.
For another example : matrices addition code here
Read More...

c++ program to add two matrices

Leave a Comment
Write a c++ program to add two matrix using 2-D arrays use any c++ compiler, turbo c++, visual studio or codeblocks.
2D arrays are just like tables which consist of rows and colums and each cell contains a value.
Matrix addition as


1     2         1     2           1+1     2+2                       2         4
            +                = >                           Result=
3     4         3     6          3+3      4+6                       6        10


Concept used:
  • const int  (Important concept here for array size)
  • 2D arrays
  • Nested for loops


Program explanation:
  • For 2D array size there must be constant value in square brackets like
    array[constant value][constant value]
  • Two const variables row and col are used to define size
    if we do not make both const then error found because without const reserve word they are
    behaving as variable.
  • Before placing both variable in square brackets they must initialized else error will be found
  • three nested for loops are used two for taking input in matrix 2D arrays and one for resultant matrix

c++ code
compiler:  
codeblocks c++ compiler



#include<iostream>
using namespace std;

int main(){

//Using const int for array size
    const int row=2,col=2;
// if not use const error found

cout<<"Size of Matrices : "<<row<<" X "<<col<<endl;
cout<<"Enter Value For First Matrix:"<<endl;

int first[row][col], second[row][col];

int i,j;
fori=0;i<row;i++){

    cout<<"Enter value for row number: "<<i+1<<endl;
    forj=0;j<col;j++){
        cin>>first[i][j];
    }

}


cout<<"\n\n\nEnter Value For Second Matrix:"<<endl;
fori=0;i<row;i++){

    cout<<"Enter value for row number: "<<i+1<<endl;

    forj=0;j<col;j++){
        cin>>second[i][j];

    }

}

// Resultant Matrix
fori=0;i<row;i++){

    forj=0;j<col;j++){
        first[i][j]=first[i][j]+second[i][j];

    }

}

cout<<"\n\n\t\tResultant Matrix:"<<endl;
fori=0;i<row;i++){
    cout<< endl;
    forj=0;j<col;j++){
        cout<<"\t\t"<<first[i][j]<<"    ";

    }

}
return 0;
}



sample input out:
c++ program to add two matrices using 2D array




This program is helpful for c++ beginners to understand the basic working of 2D arrays. It is recommended to change the code and examine the output.
Read More...

Simple Binary search code example in cpp

Leave a Comment
Write a cpp program which takes some elements in an array and a Key in variable then program use Binary Search c++ Algorithm to find the key.
Concept used:
Functions, loop, and if-else statements in c++

Program Explanation:
Program has two functions


  • One to sort array using bubble sort
  • Second to apply Binary Search on array
  • As it is necessary condition to sort the array before applying binary search in main after taking some elements as input in array. 
  • Array passes to bubble sort function to sort the array. 
  • After sorting array passes to Binary Search function which is of 'bool' type if element found in array it returns true else false to main function.

    C++ code for Binary Search

#include<iostream>
 using namespace std;

  // Prototypes of Functions
  void bubbleSort(int array[], int size);
  bool binarySearch(int array[], int size,int key);

  int main(){
      cout<<"Enter 5 numbers randomly : "<<endl;

      // Size can be change by replacing 5
      int array[5]; //Declaring array
     for(int i=0; i<5; i++)
      {
       cout<<"\t";  cin>>array[i]; // Initializing array
      }

      //Passing Arrary for Sorting
       bubbleSort(array,5);

    // Array has Sorted At This Point
    cout<<"\n\t\t\tEnter Key To Search: ";
    int key;
    cin>>key;

//Passing Array, size and key To Search Key
int result=binarySearch(array,5,key);

if(result==1)
cout<<"\n\t\t\tKey Found in Array "<<endl;
else
cout<<"\n\t\t\tKey NOT Found in Array "<<endl;


return 0;
}

void bubbleSort(int array[], int size){
      cout<<"  Input array is: "<<endl;
      for(int j=0; j<size; j++)
      {
       //Displaying Array
       cout<<"\t\t\tValue at "<<j<<" Index: "<<array[j]<<endl;
      }
      cout<<endl;
    // Bubble Sort Starts Here
     int temp;
     for(int i2=0; i2<size; i2++)
   {
     for(int j=0; j<size-1; j++)
     {
        //Swapping element in if statement
           if(array[j]>array[j+1])
       {
        temp=array[j];
        array[j]=array[j+1];
        array[j+1]=temp;
       }
     }
   }
   // Displaying Sorted array
      cout<<"  Sorted Array is: "<<endl;
     for(int i3=0; i3<size; i3++)
   {
    cout<<"\t\t\tValue at "<<i3<<" Index: "<<array[i3]<<endl;
   }
}// Sort Function Ends Here

bool binarySearch(int array[],int size, int key){
         int start=1, end=size;
         int mid=(start+end)/2;

  while(start<=end&&array[mid]!=key){
        if(array[mid]<key){
          start=mid+1;
      }
     else{
          end=mid-1;
          }
       mid=(start+end)/2;
     }// While Loop End

   if(array[mid]==key)
    return true; //Returnig to main
    else
   return false;//Returnig to main

   cout<<"\n\n\n";
}// binarySearch Function Ends Here




Sample Input Output:
Binary search code example in c++ programming tutorial

Recommended: For beginners to keep the program simple array size is small. Change the array size dry run the code on paper it will be very helpful to understand quick.
Another method to of searching






  • Linear search in C++ programming code Example

  • Recursive function in c++ linear search 
  • Read More...