Home > Software engineering >  How do you skip over a specified value within an array?
How do you skip over a specified value within an array?

Time:10-17

I am attempting to make a GPA average calculator where the user can input up to 30 GPA scores. The user has the option to continue adding GPA scores if < 30 or calculate the current GPA average with the given scores. I am trying to make my code work so that it will skip over elements within the array that contain the value 0 (inputted by the user), this way they will not be included in the sum total. I tried different if statements in order to skip over values that contained 0 but all have been unsuccessful.

Input: 10, 2, 38
Output: 16.00 (GPA average)

Input: 10, 2, 0, 38
Output: 12.00 (GPA average)
Desired Output: 16.00 <-- I want to skip over any "0" values entered by the user.

#include <stdio.h>

int main() {

int option = 0;
int iArray[30] = { 0 };
int choice;
int counter = 0;
int sum = 0;
float average;

  do {
        printf("\nEnter GPA score here: ");
        scanf(" %d", &iArray[counter]);
        counter  ;

        printf("\n1\tEnter a new GPA? Please enter \"1\".");
        printf("\n2\tCalculate the current GPA average? Please enter \"2\".\n");
        printf("\n\nPlease enter choice here: ");
        scanf(" %d", &choice);
    
  } while (choice == 1 && counter < 30);

  if (choice == 2) {
    for (int x = 0; x < counter; x  ) {
        if (iArray[x] >= 1) {   //skip over elements with value of 0
            sum  = iArray[x];
          }
      }
  }

  average = sum / counter;

  printf("\n\nThe average GPA is %.2f ", average);

  return 0;
}

CodePudding user response:

You are not adding GPAs less than 1 to your sum, but then you're average is simply dividing by the counter variable which you had counting all of the grades input.

If you introduce a new counter variable keep track of how many zero GPAs there are, you can subtract this from the overall count of grades input.

Please note that if you are dividing an int sum by an int counter, you will get an int, even if you are assigning that value to a float variable. To avoid this, cast your sum to float so that floating point math takes place.

CodePudding user response:

Its a logical issue here. Even though sum is done when values are more than 0, counter is total number of inputs.

You can maintain another counter e.g. counter_filtered and increment it only when if condition is passed.

  int counter_filtered = 0      //--> New variable
  if (choice == 2) {
    for (int x = 0; x < counter; x  ) {
        if (iArray[x] >= 1) {   //skip over elements with value of 0
            sum  = iArray[x];
            counter_filtered  ;      //--> New variable increment
          }
      }
  }

  average = sum / counter_filtered; //--> New variable usage in calculations
  • Related