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...

Binary search code in c++ programming tutorial

Leave a Comment
Write a 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...

    C++ program to find factorial of a number using recursion

    Leave a Comment
    Write a program to find the Factorial using recursive function. User will enter a number and program should display result.

    Concept  used:
    • Recursive function (returns number) int function(int n);
    • if-else statement    
    • Static variable

    How program works
    • User enters a number which stores in variable 'num'
    • Then number passes as argument in function call
    •  A static variable is used to check that how many times function is called
    • When base case becomes true if(statement) then function returns result to main
    c++ code



    #include<iostream>
    using namespace std;

    int recursive_function(int n){
        static int i=1;// to make one time initialization
        cout<<i<<" : time"<<endl; // counting the function calls

        if(n==1){
          return 1;//base case
           }
       else{
            i++;
            return  n=n*recursive_function(n-1);
            }
    }

    int main(){

        cout<<"Enter to number to find Factorial: ";
        int num;
        cin>>num;
        num=recursive_function(num)// function call
        cout<<"\n\n\n\t\t\tFactorial of number is: "<<num;
        cout<<"\n\n\n\n\n";
    return 0;
    }



    As a beginner some questions can be raised regarding code.
    Why static variable is used instead of a simple int variable?

    • The property of static variable is that it is initialized when program runs first time
    • Its value increments on every call and it is not initializing again and again
    • if we do not use static keyword then variable ' int i=1;' will be initialize again and again and its value will not be correct at the end infact it will remain 1 always. 
    • So that is why static in has been used to count the number of calls

    To provide more readable view here is image view of code:
    c++ program to find factorial using recursinve function of given number

    Sample Input Output
    sample output factorial recusion cpp
    Recommended:
    To learn fast change the code and examine output.
    Read More...

    Recursive function in c++ programming

    Leave a Comment
    This c++ tutorial contains
    • What is a recursion?
    • What are its important parts
    • A simple example code
    • How it affects stack
    Recursion in c++ programming 
    It is one of the most annoying or difficult concept for c++ programming for beginners. Yes it is difficult for a beginner to understand because sometimes its execution goes in depth where things becomes complicated and a beginners feel difficult to understand it.
    A function calls it self until a certain condition is true

    A recursive function has two important parts
    1. Base case, Stopping state, stopping condition
    2. Functions call its self with a specific conditions (Recalling condition)

    When a function calls occur in a program it pushes into the stack. So if a function is calling itself again and again (Recursive Calling) it will be pushing again and again on the stack every time it will push new resources will be allocated for a new call.

    Base Case:

    Its a condition when it becomes true or executes function stop to call it self

    Recalling Condition:
    A condition in which function recalls it  self with a specific parameters or it depends on the required result we want to get.
    • Lets write a simple example to understand the how recursive function works.
    • In this example an integer 'n' is passing to a function in which its value is incrementing by one in recalling condition.
    • When its value becomes 11 or greater than 10 (base case) it returns all calls.



    #include<iostream>
    using namespace std;
    void recursive_function(int n){

           if(n>10)   //base case 
               return;
          else{
               cout<<"Recursive Function call number "<<n<<endl;
               recursive_function(n=n+1)// here function is calling it self
              }
    }
    int main(){
      int n=1;
      recursive_function(n)// function call
    return 0;
    }

    Its output:
    Recursive function in c++ programming sample output of the code





    Lets have a look to this program it has a problem what



    #include<iostream>
    using namespace std;
    void recursive_function(){
           cout<<"I am Recursive Function"<<endl;
           recursive_function()// here function is calling it self
    }
    int main(){
      recursive_function()// function call
    return 0;
    }

    When we run the above code our program get crashes why?
    When a function is called it puts on to the stack. In the above program function is calling itself again and again and putting its calls on the stack again and again where stack is reserving some resources for each call.
    So the stacks are not in large size and when stack becomes full our program get crashes. This is why because there is not a base case in program where function will stop putting itself on stack.






    It is recommended to understand the concept do experiment with the code and analyze the output and also dry run the code on paper.  Another example in c++
    Read More...