A programming exercise

P

Phred Phungus

Stefan said:
This exercise was solved faster than I expected, and,
indeed, I had recursion in mind - similar to the solutions
posted already, so I will not post another version of mine.

While recursion might not be the most efficient solution,
it still is useful as a programming exercise for those who
have not yet grasped the concepts of recursion, automatic
and allocated storage duration in C.

$ gcc -D_GNU_SOURCE -Wall -Wextra ad3.c -o out
$ ./out
4
5
6
0
4
5
6
$ cat ad3.c
#include <stdio.h>
#include <stdlib.h>

struct list {
struct list *next;
int n;
};

int count;

static int *read_numbers(struct list *list)
{
char buf[100];
int val, i, *ret;
struct list node, *p;
if(fgets(buf, sizeof buf, stdin)) {
if(sscanf(buf, "%d", &val)!=1) {
fprintf(stderr, "That's not a number\n");
exit(EXIT_FAILURE);
}
if(val!=0) {
node.n = val;
node.next = list;
++ count;
return read_numbers(&node);
}
} else {
if(ferror(stdin)) {
perror("standard input");
exit(EXIT_FAILURE);
}
/* Naughty user sent EOF; pretend it was a 0 but with a warning */
fprintf(stderr, "Didn't get 0 terminator. List may be incomplete\n");
}

for(i=0,p=list;p;++i,p=p->next)
/*nothing*/;
ret = malloc(i * sizeof *ret);
if(!ret) {
perror("malloc");
exit(EXIT_FAILURE);
}
for(--i,p=list;p;--i,p=p->next)
ret = p->n;
return ret;
}

int main(void)

{
int i;
int *numbers,*p;
count=0;
numbers = read_numbers(0);
/* do stuff with numbers[] I guess */
p=numbers;
for (i=0; i<count; ++i) printf("%d\n",*p++);
return 0;
}

// gcc -D_GNU_SOURCE -Wall -Wextra ad3.c -o out
$

Since no one else wants it, I'll lay claim to the Stefan Ram Ramstein.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top