Solution for Exercise 06_12-pointerok.c

06_12-pointerok.c

#include <stdio.h>
#include 

int main()
{
	const int size = 5;
	int ages[size];
	int count,x;

	/* prompt */
	printf("Enter the ages ");
	printf("of everyone in your house\n");
	printf("Enter 0 (zero) to stop\n");

	/* gather input */
	count = 0;
	while(count<size)
	{
		printf("Person #%d: ",count+1);
		scanf("%d",&ages[count]);
		if( ages[count]==0 )
			break;
		count++;
	}

	/* output */
	printf("You home has people ages: ");
	for( x=0; x<count; x++ )
		printf("%d ",ages[x] );
	putchar('\n');

	return 0;
}

Output

Enter the ages of everyone in your house
Enter 0 (zero) to stop
Person #1: 8
Person #2: 13
Person #3: 15
Person #4: 37
Person #5: 38
You home has people ages: 8 13 15 37 38

Notes

* The sample output above shows the program's input maxed at 5 people. It's impossible to input more data after the fifth age is input.

* The only difference between this solution as the code in 06_11-pointero.c (from the book) is the while loop's condition. In the original code, it's an endless loop: while(1) For this solution, the loop counter is based on the value of variable count: while(count<size)

* The code could be improved by adding a message explaining that only a maximum of five ages can be input.

* The value 5 could be expressed as a defined constant, #define PEOPLE 5, with changes made where appropriate in the code.