プログラムを終了するためにセンチネル値が入力されるまで、ユーザーが検索される値を入力し続けることができるように、テスト前ループまたはテスト後ループが最適な方法であるかどうかを判断しようとしています。また、ループのパラメータはどのようになりますか? これが私のコードです。ループを含める必要があります。また、ポスト テスト ループが少なくとも 1 回実行されることも理解しています。前もって感謝します!
#include<iostream>
using namespace std;
int searchList( int[], int, int); // function prototype
const int SIZE = 8;
int main()
{
int nums[SIZE]={3, 6, -19, 5, 5, 0, -2, 99};
int found;
int num;
// The loop would be here
cout << "Enter a number to search for:" << endl;
cin >> num;
found = searchList(nums, SIZE, num);
if (found == -1)
cout << "The number " << num
<< " was not found in the list" << endl;
else
cout << "The number " << num <<" is in the " << found + 1
<< " position of the list" << endl;
return 0;
}
int searchList( int List[], int numElems, int value)
{
for (int count = 0;count <= numElems; count++)
{
if (List[count] == value)
// each array entry is checked to see if it contains
// the desired value.
return count;
// if the desired value is found, the array subscript
// count is returned to indicate the location in the array
}
return -1; // if the value is not found, -1 is returned
}