Pages

Saturday, June 29, 2013

FINDING MEDIAN AND AVERAGE IN C++

/* QUESTION :

Write a program to store integer values to a table (length of table during program execution)

using double pointer. Pass the table as arguments to a function. Print Median and average

values.

Hint: Your will use new operator to allocate memory.

Note: You have to release the memory using delete operator before the end of program. */



// CODE :


 #include<iostream>
using namespace std;

void find_median_average(double **ptr,int a,int b);

//MAIN STARTS
int main(){
 int a,b;
 cout<<"Enter the no of rows";
 cin>>a;
 double **ptr = new double *[a];

 cout<<"Enter the no of coloumns";
 cin>>b;
 for (int i=0;i<a;i++){
  ptr[i] = new double[b];
 }
 cout<<"\n\nEnter the values\n";
 for (int j=0;j<a;j++){
  for(int k=0;k<b;k++){
   cin>>ptr[j][k];
  }
 }

 find_median_average(ptr,a,b);


 for(int p=0; p< a;p++)
  delete [] ptr[p];
 delete [] ptr;
        ptr = NULL;
 return 0;
}


//END MAIN

void find_median_average(double **ptr,int a,int b){
 double average = 0;

 for (int l=0;l<a;l++){
  for(int m=0;m<b;m++){
   average += ptr[l][m];

  }
 }
 average /= (a*b);
 cout << "Average: " << average << endl;
 double median = 0;

 int positionTerm1=(a*b)/2;
 int positionTerm2=(a*b)/2+1;
 

 int count1 = 1;//How many times the loop has Run.
 int count2 = 1;
 int js = 0;
 bool breakFromInnerMostLoop = false;
 for (int i = 0; i<a; i++){
  for (int j = 0; j<b; j++){
   js = j;
   if (count1==positionTerm1){
    breakFromInnerMostLoop = true;
    break;
   }
   count1++;
  }
  if (breakFromInnerMostLoop){
    break;
  }
 }
 breakFromInnerMostLoop = false;//reset

 cout << "i: " << i << endl;
 cout << "js: " << js << endl;


 int ys = 0;

 for (int x = 0; x<a; x++){
  for (int y=0; y<b; y++){
   ys = y;
   if (count2==positionTerm2){
    breakFromInnerMostLoop = true;
    break;
   }
   count2++;
  }
  if (breakFromInnerMostLoop){
    break;
  }
 }


 cout << "positionTerm1: " << positionTerm1 << "\npositionTerm2:" << positionTerm2 << endl;
 cout << "x: " << x << endl;
 cout << "ys: " << ys << endl;
 if ((a*b)%2==0)
  cout << "Median: " << (ptr[i][js] + ptr[x][ys])/2 << endl;
 else
  cout << "Median: " <<   (ptr[x][ys]) << endl;
}

 

No comments:

Post a Comment