Lab 2 - Integer types and arrays

You will write 3 short programs in C using cygwin/gcc as your development environment. You may work together with a partner (or two) if you want, but make sure that each of you fully understands what is happening in the lab. The lab is NOT submitted.

Some guidelines for using unix command line (like cygwin) can be found here. There is also a cheat sheet for compiling with gcc here.

Your C programs will use the input functions scanf and gets. I will briefly describe them here.

scanf is more or less the input equivalent of printf, where it reads a value for each % element if the format string. For example,

   int num;
The & is necessary, we will discuss why in class. If you have any other characters in the format string, they must match exactly, so be careful.

gets reads an entire string into a char array. For example,

   char buffer[80];
Make sure that buffer is a large enough array to hold whatever value you type, including the null terminating \0. Bad things can happen (as we will see) if it is not.
Because of this danger, gcc will give you a warning about gets whenever you use it. For the early labs, we will ignore that warning and use gets with blissful ignorance.

1. Write a simple number conversion program.

Your program should prompt the user for a number and then print the number out in unsigned decimal and in hexadecimal. An example run would be:

   what is your number? 32
   32 as an unsigned value is 32
   32 as a hexadecimal value is 20

You should obviously test it with some other values as well, including a negative number.

2. Write a program to display the ASCII values for a user's string

Your program should prompt the user for a string and then print each character out in hexadecimal and decimal. An example run would be:

   what is your string? Hello
    H      e      l      l      o
   48    65    6c    6c    6f
   72  101  108  108  111

Again, test this with a number of different inputs.

3. Break a program with gets

Read the code in the attached C file. What do you think it will display if you give it a string longer than 3 characters? Compile this code into a program and try giving it different length strings as the input. Do you understand what it is doing?

Now swap the order of the two variables (num and buffer) in the breakit method. Do you think this will do anything different? Why or why not?

Rebuild the program with the swapped order and try different length strings again. Do you understand what it is doing now?

Talk to your instructor when you are either hopelessly confused or think you understand.