Classwork 4: Hello World

Objectives

To practice compiling and running your program.

The Assignment

Part 1: Modifying Hello World

  1. Use nano to edit a new file called robin.c:

    nano robin.c
    

  2. Cut and paste the "Hello World" program below into the nano window.

    #include <stdio.h>
    
    main() {
       printf("Hello World\n") ;
    }
    

  3. Save the program and exit nano. Compile the C program with:

    gcc robin.c
    

  4. Execute the program with:

    ./a.out
    

  5. Go back into nano and edit robin.c, so it prints out the following ode to Sir Robin:

    Brave bold Sir Robin
    Rode forth from Camelot.
    He was not afraid to die,
    Oh brave Sir Robin.
    

  6. Submit your program with:

    submit cs104_chang cw04 robin.c
    


Part 2: exploring %d and %f

  1. Use nano to edit a new file called print.c:

    nano print.c
    

  2. Cut and paste the program below into the nano window.

    #include <stdio.h>
    
    main() {
       double d ;
       int n ;
    
       d = 2.718 ;
       n = 32213 ;
       printf ("n = %d\n", n) ;
       printf ("d = %f\n", d) ;
    }
    

  3. Save the program, compile and run it.

  4. The program uses %d to print out the integer variable n and %f to print out the double (floating point) variable d. What happens if you print out n with %f and print out d with %d? Make those changes to your program. Save it, compile it and run it. What happened?

  5. Use the script command to record yourself compiling and executing the program. Use exit to exit from script. Now submit the modified program and typescript by:

    submit cs104_chang cw04 print.c
    submit cs104_chang cw04 typescript
    

    Make sure that your typescript file isn't empty. If typescript is indeed empty, you probably did not exit from script.

Part 3: more on %d and %f (time permitting)

  1. Use nano to edit a new file called print2.c:

    nano print2.c
    

  2. Cut and paste the program from Part 2 into the nano window.

  3. Try replacing the format code %d with %7d, %10d and %20d. (Compile and run your program after each change.) What does this formatting code do?

  4. Try replacing the format code %f with %5.1f, %5.2f, %10.4fd. (Compile and run your program after each change.) What does this formatting code do?

  5. Submit the last version of your program:

    submit cs104_chang cw04 print2.c
    


Be sure to logout completely when you have finished!