> How would you make this simple program in c?

How would you make this simple program in c?

Posted at: 2014-12-18 
You can use an array, but you will have to either start with a large array or resize the array (make a new one and copy the contents into that) if you exceed its current size.

You could also declare a char * to store the sequence as a string.

First input the numbers as integers to check for positive value.

Then convert the integer into a string value char * and append it to the char * sequence.

If you just need to output the sequence as characters, this would work. If you need the actual value of the sequence of digits, then you would have to perform more processing on the string to convert it to a value. Of course there is a limit to the number of digits you can store in a number variable.

You could also create an actual number as a long int by multiplying the variable by 10 each time you receive a new digit, then adding the digit. Again, there is a limit to how many digits you can enter until you exceed the range of the long int.

You can use an array if you know there won't be more than 30,000 numbers. It doesn't cost you anything to declare a large array. Or you could use a linked list, if you have learned about those. Or you could write the numbers to a file and then read it back in.

I would use a linked list. Something like this:

#include

struct node {

int x;

struct node *next;

};

int main()

{

struct node *root = (struct node *)malloc(sizeof(struct node));;

struct node *currentNode;

currentNode = root;

int input = 0;

printf("Enter a negative digit to stop:\n");

while (input >= 0) {

scanf("%d", &input);

currentNode->x = input;

currentNode->next = (struct node *)malloc(sizeof(struct node));

currentNode = currentNode->next;

currentNode->x = -1;

}

currentNode = root;

printf("You entered:\n");

while (currentNode && currentNode->x > -1) {

printf("%d\n",currentNode->x);

currentNode = currentNode->next;

}



return 0;

}

The user inputs numbers until a non-positive number shows up.

input:

1

2

34

5

0

Output:

1

2

34

5

0

It looks really simple, but you don't know how many inputs there are, so you can't use an array. How can you do this?

Thank you.