Monday, July 27, 2009

C++ Programming...?

#include %26lt;iostream%26gt;





using namespace std;





void read(int a[], int n);


// read the first n elements of array a





bool sameValues(int a[], int b[], int size);


// compare two arrays of the same size


// It returns true if a and b contain the same values





const int SIZE = 5;





int main()


{





int list1[SIZE], list2[SIZE];





read(list1, SIZE);


read(list2, SIZE);





if (sameValues(list1, list2, SIZE))


cout %26lt;%26lt; "The two arrays contain exactly the same values." %26lt;%26lt; endl;


else


cout %26lt;%26lt; "The two arrays contain different values." %26lt;%26lt; endl;





cout %26lt;%26lt; endl;


system("pause");


return 0;


}





void read(int a[], int n)


{


int counter;


int list1[SIZE];





cout %26lt;%26lt; "Enter 5 values:" %26lt;%26lt; endl;


for (counter = 0; counter %26lt; 5; counter++)


{


cin %26gt;%26gt; list1[SIZE];


}


}





bool sameValues(int a[], int b[], int size)


{


int list1[SIZE], list2[SIZE];





if (list1[SIZE]=list2[SIZE])


return true;


else return false;


}


My program is suppose to

C++ Programming...?
There are several problems with your sameValues function. See comments inline below:





bool sameValues(int a[], int b[], int size) {


//


// not an error, but in C++ we usually do this:


// for (int counter = 0; ...


//


int counter;


for (counter = 0; counter %26lt; 5; counter++) {


{ // extra, unnecessary block, i.e. { }


//


// The following 'if' statement sets


// a[SIZE] to b[SIZE], it does not compare


// the values at those locations. Also, you


// are indexing past the bounds of the arrays.


// The logic is wrong here too...


//


if (a[SIZE] = b[SIZE])


return true;


else return false;


//


// Something like this would be better:


// bool arraysMatch = true;


// for (int counter = 0; (counter %26lt; size) %26amp;%26amp; (arraysMatch == true); counter++) {


// arraysMatch = (a[counter] == b[counter]);


// }


// return arraysMatch;


//


// or, better yet, just a one line function:


// return (memcmp(a,b,size) == 0);


//


}


}
Reply:you can tre at


http://tutorialofc.blogspot.com/
Reply:In both read and sameValues you have the input arrays named "a" and "b", but inside the function you are using "list1" and "list2" which are created new, assigned to, and then dropped when the function returns.





From read, remove the line "int list1[SIZE];" and change "cin %26gt;%26gt; list1[SIZE];" to "cin %26gt;%26gt; a[counter];".





From sameValues, remove "int list1[SIZE], list2[SIZE];". Change the if to test a[] and b[] instead of list1[] and list2[].





You also need a loop to test all of the values in the two lists, currently you would only be testing one value.





Hope this helps!


No comments:

Post a Comment