简体   繁体   中英

Input scanf array with recursively function without loops (.c)

The user get me the size of the array, and i am allocate with function "MALLOC" the memory allocation and get input the array with recursion only, without loops!!

I do not know how to create a "loop" with recursion function.

I hope happy to get help please.

thanks.

That's not a good use of recursion - a loop is more "natural" in this case - but the idea would be a function like this:

void getInput(int howMany)
{
  if (howMany == 0)
    return;
  // get user input
  getInput(howMany-1);
}

Because this seems like homework, I'll give a homework-oriented answer -- in pseudo-code.

define loop(array, index)
    if index == 0
        return array
    array[index] = get input from user
    loop (array, index-1)

Call it with loop(array, array_size) .

I'd like to echo Mat's sentiment that this is not a good use of recursion.

Update

Since you'd like to use scanf(3) to read the input, I'll give a stronger hint on how to use it. Above, I wrote:

    array[index] = get input from user

You could write this line with the following scanf(3) call:

scanf("%d", &array[index]);

This will store a decimal integer into the array[index] location -- the & returns the address of the array slot, rather than evaluating the array subscription.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM