switching for-loops to while-loops

This commit is contained in:
Dan Buch 2011-09-19 23:09:29 -04:00
parent a584141d4d
commit 4d824d341f

20
ex15.c
View File

@ -5,9 +5,10 @@ void print_with_array_indexing(int count, char **names, int *ages)
int i = 0; int i = 0;
// first way using indexing // first way using indexing
for(i = 0; i < count; i++) { while(i < count) {
printf("%s has %d years alive.\n", printf("%s has %d years alive.\n",
names[i], ages[i]); names[i], ages[i]);
i++;
} }
printf("---\n"); printf("---\n");
@ -15,15 +16,16 @@ void print_with_array_indexing(int count, char **names, int *ages)
void print_with_pointer_arithmetic(int count, char **names, int *ages) void print_with_pointer_arithmetic(int count, char **names, int *ages)
{ {
int i; int i = 0;
// setup the pointers to the start of the arrays // setup the pointers to the start of the arrays
int *cur_age = ages; int *cur_age = ages;
char **cur_name = names; char **cur_name = names;
// second way using pointers // second way using pointers
for(i = 0; i < count; i++) { while(i < count) {
printf("%s is %d years old.\n", printf("%s is %d years old.\n",
*(cur_name+i), *(cur_age+i)); *(cur_name+i), *(cur_age+i));
i++;
} }
printf("---\n"); printf("---\n");
@ -31,13 +33,14 @@ void print_with_pointer_arithmetic(int count, char **names, int *ages)
void print_with_pointers_as_arrays(int count, char **names, int *ages) void print_with_pointers_as_arrays(int count, char **names, int *ages)
{ {
int i; int i = 0;
int *cur_age = ages; int *cur_age = ages;
char **cur_name = names; char **cur_name = names;
// third way, pointers are just arrays // third way, pointers are just arrays
for(i = 0; i < count; i++) { while(i < count) {
printf("%s is %d years old again.\n", printf("%s is %d years old again.\n",
cur_name[i], cur_age[i]); cur_name[i], cur_age[i]);
i++;
} }
printf("---\n"); printf("---\n");
@ -50,12 +53,9 @@ void print_in_stupidly_complex_way(int count, char **names, int *ages)
char **cur_name = names; char **cur_name = names;
// fourth way with pointers in a stupid complex way // fourth way with pointers in a stupid complex way
for(cur_name = names, cur_age = ages; while((cur_age - ages) < count) {
(cur_age - ages) < count;
cur_name++, cur_age++)
{
printf("%s lived %d years so far.\n", printf("%s lived %d years so far.\n",
*cur_name, *cur_age); *cur_name++, *cur_age++);
} }
printf("---\n"); printf("---\n");