CS 2420-20 Homework 2

Due: Tuesday, January 25th, 2011 9:10am

Handin five files for this assignment, one for each part.

Part 1 – Swap Integers

Use this code as swapint.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  /* define a swap function here .... */
  
  int main(int argc, char** argv) {
     int a = atoi(argv[1]);
     int b = atoi(argv[2]);
  
     swap(&a, &b);
  
     printf("%d\n", a);
     printf("%d\n", b);
  
     return 0;
  }

Implement swap so that the resulting program takes two small integers on the command line and prints them in reverse order.

Part 2 – Swap Strings

Use this code as swapstr.c:

  #include <stdio.h>
  
  /* define swap .... */
  
  int main(int argc, char** argv) {
     char* a = argv[1];
     char* b = argv[2];
  
     swap(&a, &b);
  
     printf("%s\n", a);
     printf("%s\n", b);
  
     return 0;
  }

Implement swap so that the resulting program takes two command-line arguments (that can be anything) and prints them in reverse order.

Part 3 – String Comparison

Use this code as strcmp.c:

  #include <stdio.h>
  
  int same_string(char* a, char* b) { .... }
  
  int main(int argc, char** argv) {
     if (same_string(argv[1], "hello") == 0)
       printf("hi\n");
     else
       printf("huh?\n");
  
     return 0;
  }

Implement same_string so that it returns 0 if its arguments are the same string, 1 otherwise. The C language provides functions like strcmp and strlen, but don’t use them.

Part 4 – Array Allocation

Use this code as array.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  int* make_array(int len) { .... }
  
  int main(int argc, char** argv) {
     int len;
     int *a;
     int i;
  
     len = atoi(argv[1]);
     a = make_array(len);
  
     for (i = 0; i < len; i++) {
       if (a[i] != i)
         printf("bad\n");
     }
  
     return 0;
  }

Implement make_array so that it when a small natural number is provided as a command-line argument, the prgram does not print “bad.” You’ll need to use malloc in make_array.

Part 5 – Matrix Allocation

Use this code as matrix.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  int** make_matrix(int rows, int cols) { .... }
  
  int main(int argc, char** argv) {
     int rows, cols;
     int **m;
     int i;
     int j;
  
     rows = atoi(argv[1]);
     cols = atoi(argv[2]);
  
     m = make_matrix(rows, cols);
  
     for (i = 0; i < rows; i++) {
       for (j = 0; j < cols; j++) {
         if (m[i][j] != i+j)
           printf("bad\n");
       }
     }
  
     return 0;
  }

Implement make_array so that it when two small natural numbers are provided as command-line arguments, the prgram does not print “bad.” It’s easiest to use malloc more than once in make_matrix.


Last update: Thursday, April 7th, 2011
mflatt@cs.utah.edu