CS 2420-20 Homework 3

Due: Tuesday, January 24th, 2012 9:10am

Handin four 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 – Count Command-Line Argument Characters

Write a program count.c that counts the total number of characters in all command-line arguments. The program should prints out the count.

Examples, assuming that the program is compiled as count:

  % ./count a b c
  3
  % ./count a bbb c
  5
  % ./count a "b x y z" cc
  10

Last update: Tuesday, January 24th, 2012
mflatt@cs.utah.edu