Computer Scientists are Pretty Pessimistic

Friday 6 November 2015

Write a code to search for a value in the matrix and change it with user given value. Your code should give the position of that number too. User will give 2 inputs: 1.) What value to change/search and 2.) What is the new value.

                
                    Suppose C=[1 3 5;2 4 6;9 8 7]


Solution :: Code :: This code is written with C++ ;


#include <iostream>
using namespace std;
int main ()
{
    int mat[3][3] ={1,3,5,
                    2,4,6,
                    9,8,7};
    int change,value,i,j,p,q,f=0;
    cout<<"Enter which value you want to change: ";
    cin>>change;

    cout<<"Enter value: ";
    cin>>value;

    for(i=0;i<3;i++) // search and change value
    {
        for(j=0;j<3;j++)
        {
            if(mat[i][j]==change)
                {
                    mat[i][j]=value;
                    p=i;
                    q=j;
                    f=1;
                    break;
                }
        }
        if(f==1) break;
    }
    if(f==1)
    {
        cout<<"The new matrix is:"<<endl;
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                cout<<mat[i][j]<<" ";
            }
            cout<<"\n";
        }
        cout<<"The position of changed number is: ("<<p+1<<","<<q+1<<")\n";
    }
    else
        cout<<"Number not found"<<endl;

    return 0;
}

No comments:

Post a Comment