Basic arithmetic, input/output, and conditionals and loops


Exercise 1

Read the C Programming textbook for input/output using the following standard C functions:

You should also use the man command to read the online manual pages for each of these functions.

Write a program that does the following: It prompts the user to enter a number from 1 to 5, reads the response, and then prints "Hello World" (with a newline at the end) as many times as indicated by the user's response. That is, if the user enter 3, then your program will print "Hello World" three times on three different lines.

Run this program with three different inputs, and show the output obtained.


Exercise 2

Write a program that requests three single-precision floating point numbers (floats), and prints their sum and product to four decimal places.

Show the output of your program by running it on five different sets of input.


Exercise 3

Write a program that requests six integers, reads all of them, then prints all of them in the following format: (i) first print a header line as shown in the example below; then (ii) two integers per line, with each integer right-justified in a field of 10 characters, separated by two blank spaces. For example, if the numbers input are 1, 10, 20, 25, 1000, -200, then the output should be exactly as follows:

1234567890bb1234567890
         1          10
        20          25
      1000        -200

Show the output of your program by running it on two different sets of input.


Exercise 4

Write a program that repeatedly reads an integer, and determines if it is prime or non-prime. Specifically, the program should do the following:

Note that the C language provides / and % operators for integer divide and modulus operations.

For example, the following is one execution scenario:

Number [1-100]: ? 5
Prime
Number [1-100]: ? 1
Prime
Number [1-100]: ? 2
Prime
Number [1-100]: ? 27
Non-prime, divisible by 3
Number [1-100]: ? 0
Done

First test your program by running it through the execution scenario above, and make sure it produces exactly the same output. Next, run your program with an input of your choice (5 different numbers before ending with a 0), and show the output.


Written: 26 January 2011, Montek Singh, montek@cs.unc.edu