[Courses] [C] Lesson12: Exercise answers

Morgon Kanter admin at surgo.net
Wed Nov 20 22:51:03 EST 2002


[1] Write a program that uses pointers to set each element of an
    array to zero.
/* Not sure if this is EXACTLY what you were looking for,
 * but here goes. */
#include <stdio.h>

/* Obviously, the prototype. I put them all above the first function,
 * below the typedefs. */
void array_to_zero(int *array, unsigned int number_of_elements);

int main() {
   /* as you can probably guess, I try to be sparing of resources.
    * Even though this is 2002, not the < 1990 */
   unsigned short i;
   int array[5] = {5,3,2,7,-4};

   /* Output what the array is right now */
   puts("Entering first loop...");
   for(i=0;i<5;i++) printf("array[%i] is %i\n", i, array[i]);
   putchar('\n');

   array_to_zero(array, 5);

   /* Output what it is now (all 0s) */
   puts("Entering second loop...");
   for(i=0;i<5;i++) printf("array[%i] is %i\n", i, array[i]);
   putchar('\n');

   return 0;
}

void array_to_zero(int *array, unsigned int number_of_elements) {
   unsigned int i;

   for(i=0;i<number_of_elements;i++) {
      *array = 0;
      array++;
   }
}
/* End */

[2] Write a function that takes a single string as its argument and
    returns a pointer to the first nonwhite character in the string.
/* Begin */
#include <stdio.h>

char *stringlook(char *string);

int main() {
   char string[80];
   char *stringpointer;
   unsigned short int i;

   printf("Enter a string: ");
   fgets(string, sizeof(string), stdin);

   /* trim off the newline character here */
   for(i=0; string[i] != '\0'; i++) {
      if(string[i] == '\n') {
         string[i] = '\0';
         break;
      }
   }

   printf("String reads: %s\n", string);
   stringpointer = stringlook(string);
   printf("Pointer reads: %c\n", *stringpointer);

   return 0;
}

/* Searches the string for the first non-white character and
 * returns a pointer to it. If there is none, it returns 1. */
char *stringlook(char *string) {
   unsigned short i;

   for(i=0; *(string+i) != '\0'; i++) {
      if( *(string+i) != ' ') return (string+i);
   }

   return 1;
}
/* End */
--
Fetch my UPDATEd public key from http://www.surgo.net/pubkey.asc




More information about the Courses mailing list