Home > Software design >  In C, how do I print the index of however many values the user chooses to input?
In C, how do I print the index of however many values the user chooses to input?

Time:11-03

I am essentially attempting to print out how many values are entered for the array in this code (If they enter 10 numbers, I would want to print for index: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 as well as taking user inputs for the array values and printing those in a table-like fashion beside of their index). How would I go about doing this, and is there anything wrong with this code?

#include <stdio.h>
#include <stdlib.h>

int arr_1 (int ar[], int size);

int main()
{
    double sentinel[20];

    printf("Hello User!\n\nEnter up to 20 values, and type -1 when you are finished: ");

    for (int i = 0; i < 20;   i) {
        scanf("%lf", &sentinel[i]);
    }

    for (int i = 0; i < 20;   i) {
        printf("%f\n", sentinel[i]);
    }

    printf("\n%lu\n", sizeof(sentinel[20]));
}

int arr_1 (int ar[], int size)
{
    return 0;
}

CodePudding user response:

First, you will need to check whether the user actually inputs as many values as you expect to get (20 in your case). The scanf() function tells you, in its return value, whether it actually managed to parse another number from the input.

Then, you'll need to exit your loop when no more numbers are available on the input.

Finally, you'll need to keep track of how far you got in the loop. One way to do this is to define the loop index (i) in the scope outside the loop. That way it's not lost to you when the loop is eventually cleared.

Once you have the last i value (suppose you assign it to a new variable like so, int num_input_elements = i 1) then you know your indices are 0, 1,... num_input_elements - 1. And you can easily loop through those, printing, in fact, your loop index.

Additional notes:

  • Don't use the "magic number" 20 all over. Use a preprocessor definition before you first use it, e.g. something like #define MAX_NUM_ELEMENTS 20.
  • sentinel is a confusing name for your array, because a sentinel typically means something else in programming.
  • sizeof(sentinel[20]) is always sizeof(double)... not the number of elements you got on the input.
  • Related