Challenge: Read Until Zero
Completed
Read whole numbers until a 0 appears (the 0 is not part of the list). Store them in a list that starts with room for 2 and doubles with realloc when full. Then print the numbers in reverse order on one line, separated by spaces. If the list is empty, print empty.
Input
Integers, ending with 0.
Output
The numbers in reverse, or empty.
Example
Input
1 2 3 4 5 0
Output
5 4 3 2 1
Editor
C
Hints
Keep two numbers: how many items you have (count) and how many fit (capacity).
When count == capacity, double capacity and call realloc.
Solution explanation
Doubling means the list only has to grow a few times, even for many numbers.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int capacity = 2;
int count = 0;
int *list = malloc(capacity * sizeof(int));
int x;
scanf("%d", &x);
while (x != 0) {
if (count == capacity) {
capacity *= 2;
list = realloc(list, capacity * sizeof(int));
}
list[count] = x;
count++;
scanf("%d", &x);
}
if (count == 0) {
printf("empty\n");
} else {
for (int i = count - 1; i >= 0; i--) {
printf("%d", list[i]);
if (i > 0) {
printf(" ");
}
}
printf("\n");
}
free(list);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module