Test 3 : C++ code solution for Q5 and Q6
C++ code solution for Q5 and Q6 using Assertions
This is the full working code as the solution for Q5 and Q6
#include <assert.h> #include <iostream> using namespace std; /* * Pre conditions: intArray is not NULL * arrsize is more than zero * Post conditions: returns the index of the number * if the number is found in the array * else returns -1 * Invariants: returned index will be between 0 - arrsize or -1 */ int search(int *intArray, int arrsize, int number) { //check pre conditions using assertions assert(intArray != NULL); assert(arrsize != 0); //method implementation int index = -1; for (int i = 0; i < arrsize; i++) { if (intArray[i] == number) { index = i; break; } } return index; } int main() { //There are three test cases to test this code enable these test cases //by removing the comments and disable the others by putting comments //Test Case 1 - test assertion for null array check //Code to test first assertion in the above search() method int *arr = NULL; int index = search (arr, 3, 7); //End of Test Case 1 //Test Case 2 - test assertion for arraysize value //Remove comments on the two lines below to test the second assertion //int arr[] = {0,3,7}; //int index = search(arr, 0, 7); //End of Test Case 2 //Test Case 3 - test the method implementation /* Remove the comments below to test method implementation int array[] = {0,3,7}; int *arr = array; int index = search(arr,3,7); cout << index << endl; //End of Test Case 3 */ }
page revision: 0, last edited: 28 Dec 2009 15:45