0

My code works fully but for full credit we need to include a comma after every number except the last one. I'm not sure where I should place it seeing as where ever it ends up either in the for loop or out, it does not produce the correct look.

My code produces 25 0 33 like it should be needs to look like 25, 0, 33

Sample inputs: 5 25 51 0 200 33 0 50

    #include <stdio.h>

int main() {
   
   int numVals;
   int max, min;
   
   printf("How many integers to enter?\n");
   scanf("%d", &numVals);
   
   int array[numVals];
   
   printf("Please enter %d integers: \n", numVals);
   
   for (int i = 0; i < numVals; ++i) {
      scanf("%d", &array[i]);
   }
   
   printf("Lower and upper bounds: \n");
   scanf("%d %d", max, min);
   
   for (i = 0; i < numVals; ++i) {
      if (array[i] >= min && arr[i] <= max {
         printf("%d", array[i]);
      }
   }
   
   return 0;
}
3
  • 1
    In your loop, can you determine if you're on the last iteration? If you can, then only print a trailing "., " if that's not true. Commented Oct 6, 2021 at 2:03
  • 5
    It's easier to determine whether you're on the first iteration, and then only print a leading comma if that's not true. Commented Oct 6, 2021 at 2:05
  • Your other alternative is printf (i>0?", %d":"%d", array[i]); By setting the i>0 condition, branch prediction will minimize the impact of the conditional only taking the false path of the ternary on the first iteration. Commented Oct 6, 2021 at 3:24

1 Answer 1

6

A simple way is to change the separator after the first number.

 const char *sep = "";
 for (i = 0; i < numVals; ++i) {
    if (array[i] >= min && arr[i] <= max) {
       printf("%s%d", sep, array[i]);
       sep = ", ";
    }
 }
 prinf("\n");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.