Michael Wendel Michael Wendel - 7 days ago 8
C Question

How to get an input function for an array to terminate based upon a specific input and size?

I have an input function for an array that is initialized to contain 50 elements. The loop that is collecting input from the user terminates once the value "-1" is entered and 50 entries are entered in.

In order to test the program correctly I have these 2 test cases:


  1. There are less than 50 values entered and the data set ends with "-1".

  2. There are 50 values entered and the data set doesn't end with a "-1".



I'm able to get the 1st test case to work, but for the 2nd test case it appears to go into an infinite loop. How would I modify my input function to work for the 2nd test case as well?

Main Function:

#include<stdio.h>
#include<stdlib.h>
//Global Declarations
#define SIZE 50

int getFuelRange();
int getStartMile();
void getMileMarkers(int markers[], int*);
void bubbleSort(int markers[], int);
int searchArray(int markers[], int, int);
int calcDifference(int markers[], int, int, int);
int findSize(int markers[]);
//void displayResults();

int main()
{
//Local Declarations
int fuelRange;
int startMile;
int markers[SIZE];
int i = 0;
int points;
int size;

//Executable Statements
fuelRange = getFuelRange();
startMile = getStartMile();
getMileMarkers(&markers[i], &size);
//Diagnostics
//printf("\nFuel Range: %d Start Mile: %d\n", fuelRange, startMile);
//printf("\nSize: %d \n", size);
points = calcDifference(&markers[i], fuelRange, startMile, size);


//Diagnostics
//printf("\nFuel Range: %d Start Mile: %d\n", fuelRange, startMile);
printf("Points: %d \n", points);

return(0);
}


Input Function:

void getMileMarkers(int markers[], int *size)
{
//LOCAL DECLARATIONS
int i = -1; //counter
//EXECUTABLE STATEMENTS
printf("Enter mile marker positions: ");
do
{
i++;
scanf("%d", &markers[i]);
//Diagnostic Print
printf("\n%d", markers[i]);
}while(markers[i] != -1 && i < SIZE);
(*size) = i;
}


Any help is appreciated! Thank you!

Answer

Much easier and more readable to just have a do-loop and exit if the marker is found:

for ( i=0; i < SIZE; i++ ) {
   scanf("%d", &markers[i]);
   if ( markers[i] == -1 ) {
      break;
   }
}