Pregunta

I am trying to figure out whether a pre or post test loop would be the best method so that the user can continue to input values that will be searched for, until a sentinel value is entered to end the program. Also, what would my parameters look like for the loop? Here is my code, I need to include the loop. Also, I understand that a post test loop is executed at least once. Thanks in advance!

#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
  }
¿Fue útil?

Solución 2

I must say, I'm not entirely sure what you want to know. I would honestly recommend a good book on C++. Post test loops are not super popular in C++ (they are of the form "do.. while" where "while" loops / pre test loops are much more common). A little more information is available here: "Play It Again Sam"

EDIT: you need to get data from the user, test it, and then do stuff based on it. Your best bet is something along the lines of

 static const int SENTINEL = ??;
 int num;

 cout << "please input a number" << endl;
 cin >> num;
 while( num != SENTINEL ) {
      // DO STUFF HERE

      // Now get the next number
      cout << "please input a number" << endl;
      cin >> num;
 }

Otros consejos

Your question is more of a use case dependent.

Post Case: When you need the loop to run AT LEAST once ( 1 or more times)

Pre Case: The loop can run 0 or more times.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top