Sunday, August 2, 2009

Below is my C++ code and question,but it cannot compiled.plz help me check this program?

A. Write a function that takes an array and its size as arguments, searches the array for the largest element, and sets that element to zero; the function should return the value that used to be in that spot (before it was set to zero).


B. In your main program, create an array of 20 integers, and give them all random positive values (in the range 1-100). Print out the contents of the array. Then, call the function you wrote in A ten times; print out the total of all the numbers returned by the function, and then print out the contents of the array again.





#include %26lt;iostream%26gt;


using namespace std;





int largestElement(int array[], int size)


{


int i;


int j;


int largest=0;





for(i=0;i%26lt;size-1;i++)


{


if (array[i]%26gt;largest)


{


largest = array[i];


}


}





for(j=0;j%26lt;size-1;j++)


{


if(array[j]==largest)


{


array[j]=0;


return largest;


}


}


}

Below is my C++ code and question,but it cannot compiled.plz help me check this program?
#include %26lt;time.h%26gt;


#include %26lt;iostream%26gt;


using namespace std;





int largestElement(int numbers[], int size)


{


 int largestNum = -1, largestIdx = 0;





 for(int i = 0; i %26lt; size; i++)


 {


  if(numbers[i] %26gt; largestNum)


  {


   largestIdx = i;


   largestNum = numbers[i];


  }


 }





 numbers[largestIdx] = 0;





 return largestNum;


}








int main(int argc, const char* argv[])


{


 int i, nums[20], sum = 0;





 srand((unsigned) time(NULL));





 for(i = 0; i %26lt; 20; i++)


 {


  nums[i] = 1 + rand() % 99;


  cout %26lt;%26lt; nums[i] %26lt;%26lt; " ";


 }





 for(i = 0; i %26lt; 10; i++)


 {


  sum += largestElement(nums, 20);


 }





 cout %26lt;%26lt; endl %26lt;%26lt; sum %26lt;%26lt; endl;


 for(i = 0; i %26lt; 20; i++)


 {


  cout %26lt;%26lt; nums[i] %26lt;%26lt; " ";


 }





 return 0;


}


No comments:

Post a Comment