Growing Array

Lab C Advanced 30 points

Read integers until -1 into a dynamic array that starts with capacity 2 and doubles with realloc when full. Print the count, the final capacity, and the numbers.

Input

Integers, the last is -1.

Output

Three lines.

Example

Input

5 6 7 8 9 -1

Output

5
8
5 6 7 8 9
Sample input available Sample output available
Editor
C

Hints

When count reaches capacity, double the capacity and realloc.

Solution explanation

Doubling keeps the number of reallocations small - it's how resizable arrays (like C++ vector) work.

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

int main() {
    int capacity = 2, count = 0, x;
    int *a = malloc(capacity * sizeof(int));
    scanf("%d", &x);
    while (x != -1) {
        if (count == capacity) {
            capacity *= 2;
            a = realloc(a, capacity * sizeof(int));
        }
        a[count] = x;
        count++;
        scanf("%d", &x);
    }
    printf("%d\n%d\n", count, capacity);
    for (int i = 0; i < count; i++) printf("%d ", a[i]);
    printf("\n");
    free(a);
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD