Homework 2: Input & Output
Due: Tuesday 2/14 by 11:59pm
More practice with printf() and scanf()
Write a program that asks the user for the user's name and the user's height in inches. Your program then replies with the user's name and height in feet and inches (not in centimeters like we did in Classwork 3). A sample run of your program might look like this: (The user's response is in orange.)
PT% gcc -Wall height2.c PT% ./a.out What is your name? Percival How tall are you in inches? 79 Hello, Percival. You are 6 feet and 7 inches tall. PT%
- Please name your C program height2.c
- A good starting point is your program from Classwork 3.
- You will want to use the division operator / and the modulus operator %. In C, when you divide two integer values, the remainder is thrown out. For example, 17 / 5 gives you 3.
- The modulus operator calculates the remainder of a division. For example, 17 % 5 gives you 2.
- Think about how get 6 feet and 7 inches from 79 inches in the sample run above, using the / and % operators.
Write a program that asks the user for the user's name and the user's
height in centimeters then replies with the
user's name and height in feet and inches.
(This time you are converting from metric to the English system.)
PT% gcc -Wall height3.c
What is your name? Gawain
How tall are you in centimeters? 195
Hello, Gawain. You are 6 feet 5 inches tall.
- A good starting point is your program from Part 1. Make a copy of the program using the Unix cp command. You will need to submit both programs. Please name this program height3.c
- First convert centimeters to inches, then the same code from Part 1 would work.
- When you divide an integer value by a floating
point value, you get a floating point value. If you assign
a floating point value to an integer variable, the fractional
part is thrown away. So, mathematically
10 / 2.54 is 3.937... but if you assign this to an integer
variable, you get 3. For example, after the assignment
n = 10 / 2.54 ;the integer variable n would have value 3. To achieve rounding, you can add 0.5 to the calculation:
n = 10 / 2.54 + 0.5 ; m = 8 / 2.54 + 0.5 ;The n would hold 4 and m would hold 3. (Assuming that both n and m are int variables.)
- If you need a new variable, you have to declare it with int or double at the beginning of the program (after main()).
What to submit
Use the script command to record yourself compiling both programs and running each program 3 times. Use exit to terminate the recording. Then submit your programs and typescript file:
submit cs104_chang hw02 height2.c height3.c typescript