Basic arithmetic, input/output, and conditionals and loops


Your assignment must be submitted electronically by 11:59pm on Wednesday, September 13.


Exercise 0

Prior to beginning this tutorial, carefully review the description of the following input/output functions:

Relevant readings are:

You should also use the man command to read the online manual pages for each of these functions (use the spacebar to scroll to the next page, 'b' to the previous page, up/down arrows to scroll a line, and 'q' to quit).

% man scanf

Make sure you understand the format strings used by scanf() and printf() to specify the format of the input/output, especially reading/writing characters, strings, integers, and floats. Make sure you understand how the width (i.e., number of characters used) is specified in a format string, and also how left- vs. right-justification is specified.

A good summary of the formatting specifiers for scanf() and printf() is available here: http://www.cplusplus.com/reference/cstdio/scanf/ and http://www.cplusplus.com/reference/cstdio/printf/.

In the exercises below, you will only need the scanf and printf functions, but you will use the others listed above in future assignments.

Important Tip: When printing using printf, you need to specify within the format string all the white spaces you would like printed. For example, printf("%d  %f\n\n", 1, 2.1); prints the integer 1 and float 2.1 separated by two spaces, followed by two newlines. However, when reading the same, you will use scanf("%d%f", &i, &f);, without specifying any white spaces between the integer and the float being read. This is because the scanf function, when reading numbers, skips over all white space before the start of the number, exactly as would be expected of such a routine. So, it would correctly read i and f regardless of whether they were separated by one space, two spaces, three tabs, five newlines, etc. However, if you were to write scanf("%d  %f\n\n", &i, &f);, then the function will expect (at least) two spaces between the numbers, and two newlines afterward.

So, in summary, avoid spaces in the format string for scanf, but provide exact spacing/newlines in the format string for printf.


Note

For the exercises below, create a folder lab2 inside the comp411lab folder that you already have under your home directory. For the exercises below, you will code your C programs in the files ex1.c, ex2.c, ex3.c, ex4.c and ex5.c, respectively. Sample input and output files are provided in the folder /home/montek/comp411/samples/lab2.


Exercise 1

Write a program that does the following: It prompts the user with "Please enter a number from 1 to 5:\n" (note the newline after the colon), reads the user's response, and then prints "1 Hello World" (with a newline at the end), "2 Hello World", "3 Hello World", etc. as many times as indicated by the user's response, and terminates. If the user enters a number that is outside of the 1..5 range, the program should print the error message "Number is not in the range from 1 to 5" (with a newline at the end), and terminate.

The file with your C program should be called ex1.c, and the compiled version called ex1. Compile the C program using the C compiler (cc or gcc), and test it with a few different inputs. You can find sample test input and output files as described above. Below is one execution scenario (program output is blue and input is red):

Please enter a number from 1 to 5:

3

1 Hello World

2 Hello World

3 Hello World


Exercise 2

Write a program that requests five single-precision floating-point numbers (floats), and prints their sum, arithmetic mean, and product to 4 decimal places. Specifically, the program should prompt the user with this message "Enter five floating-point numbers:\n" (note the newline after the colon). It should print the sum, mean and product formatted exactly as shown (to 4 decimals):

Enter five floating-point numbers:

1.45 -2e2 -2e-2 14 -10.0

Sum is -194.5700

Mean is -38.9140

Product is -812.0000

Name the file with the C program ex2.c. Compile it, save the executable as ex2, and test it on the sample input and output files provided.


Exercise 3

Write a program that requests six integers ("Enter six integers:\n") (note newline after colon), 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. Each of the integers supplied could be in either decimal, octal or hexadecimal format, and your program should read it correctly. For output, each integer should be printed in decimal format.

For example, if the numbers input are 1, 010, 0x20, 25, 1000, -200, then the output should be exactly as follows:

Enter six integers:

1 010 0x20 25 1000 -200

1234567890bb1234567890

1 8

32 25

1000 -200

Name the file with the C program ex3.c. Compile it to ex3 and test it on the sample input and output files provided.

Tip 1: Carefully study the format specifiers (%i, %d, %u, %o, %x) for scanf() from the reference provided above (http://www.cplusplus.com/reference/cstdio/scanf/).

Tip 2: Carefully study the width specifier for printf() from the reference provided above (http://www.cplusplus.com/reference/cstdio/printf/). There is an example on that page showing how to print a number into a field of 10 characters, preceded by blanks.


Exercise 4

Now redo Exercise 3 so that all integers in the input are strictly interpreted as decimal numbers, even if they start with a leading '0'. (The input will not contain any hex numbers starting with '0x'.) Tip: Carefully choose the format specifier (%i, %d, %u, %o, %x) for scanf().

For example, if the numbers input are 1, 010, 00020, 25, 1000, -200, then the output should be exactly as follows:

Enter six integers:

1 010 00020 25 1000 -200

1234567890bb1234567890

1 10

20 25

1000 -200

Name the file with the C program ex4.c. Compile it to ex4 and test it on the sample input and output files provided.


Exercise 5

Write a program that repeatedly reads an integer in decimal format, 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 ?

5

5 is a prime

Number ?

1

1 is non-prime (special case)

Number ?

2

2 is a prime

Number ?

027

27 is non-prime, divisible by 3

Number ?

0

Done

First test your program by running it through the execution scenario above, and make sure it produces exactly the same output. Name the file with the C program ex5.c. Compile it to ex5 and test it on the sample input and output files provided.


Exercise 6

Write a program that repeatedly reads an integer in decimal format, and determines if it is a triangular number or not. A triangular number Tn is defined as 1+2+3+...+n. For more on triangular numbers, see this Wikipedia article.

Specifically, the program should do the following:

For example, the following is one execution scenario:

Number ?

1

1 is a triangular number

Number ?

2

2 is not a triangular number

Number ?

3

3 is a triangular number

Number ?

20

20 is not a triangular number

Number ?

21

21 is a triangular number

Number ?

0

Done

First test your program by running it through the execution scenario above, and make sure it produces exactly the same output. Name the file with the C program ex6.c. Compile it to ex6 and test it on the sample input and output file provided (ex6in1).


Testing

Sample Inputs and Outputs

Sample inputs and corresponding outputs are provided under /home/montek/comp411/samples/lab2. You should try running your program on the sample input files provided, and make sure the program's output is identical to that in the sample output files.

First, copy all the sample input and output files to your lab2 folder:

% cd ~/comp411lab/lab2
% cp /home/montek/comp411/samples/lab2/* .

(Note the dot at the end of the cp command above.)

To see what these files contain, you can use any of these methods:

Compiling your source code

Use the following commands to compile your C programs (e.g., ex1.c) and create the executables (e.g., ex1):

% gcc ex1.c -o ex1
% gcc ex2.c -o ex2

... and so on.

Running your executable

First, try to run your executable (% ./ex1), and provide it input from the terminal and observe the output. If everything looks good, you can use the following commands to run with our sample inputs. These commands send the output of your program directly to the terminal.

% ./ex1 < ex1in1
% ./ex1 < ex1in2

... and so on.

Now, we will capture the program output into files so we can carefully examine them and compare against the sample outputs provided:

% ./ex1 < ex1in1 > ex1result1
% ./ex1 < ex1in2 > ex1result2

... and so on. Repeat for each sample input file, and repeat for each exercise.

Check the output

You can examine your program output captured in the *result* files by using cat, less or pico, as explained above:

% cat ex1result1

% less ex1result1

% pico ex1result1

Compare your output with the sample output files provided (ex1out1, etc.) to be sure they match exactly.

Using diff

diff is a very powerful utility for comparing the contents of files, and can be used with several different options:

Use the diff command to determine any differences between your program's output (which you redirected into the file ex1result1) and the correct output provided to you (in the file ex1out1). Watch out for extra spaces at end of lines, etc.!

For example:

% diff -qs ex1result1 ex1out1

... and so on. Repeat for each sample input file, and repeat for each exercise.

Before submitting your work, be sure that each of your compiled programs runs correctly on all of the sample inputs provided exactly, i.e., diff reports no differences at all. You may receive zero credit if your program's output does not exactly match the sample outputs provided.

If diff produces errors, please manually inspect your output and the provided output to see what is different. You can use cat or pico to see the contents of the files.

Using hexdump

If the differences are due to white space errors only, it is sometimes hard to find the extra spaces, especially if they are at the end of a line. For that purpose, use hexdump -c filename to dump the contents of the file onto the terminal; it will show the ASCII codes of each character, and make it easy to see trailing white space at the end of lines:

% hexdump -c ex1result1

% hexdump -c ex1out1

Final check before submitting

You can also check your entire Lab 2 (without actually submitting it) by running the self-check script (see below).


Due Date and Submission Procedure

Due Date: 11:59pm on Wednesday, September 13. You will submit your work on Exercises 1-6. Specifically, the files ex1.c, ex2.c, ex3.c, ex4.c, ex5.c and ex6.c will be collected.

How to submit: Navigate to the folder where these files are stored (~/comp411lab/lab2), and run the following command for running a self-checking script (which does not submit the files):

% cd ~/comp411lab/lab2
% /home/montek/comp411/bin/selfchecklab2

If the self-check did not report any errors, you can submit your work as follows:

% cd ~/comp411lab/lab2
% /home/montek/comp411/bin/submitlab2

When you invoke the submit script, it submits your files, and once again performs a quick check on your source files (including compiling, running and comparing the output of your program with the expected output, for all sample input/output files), and provides a quick summary of any errors. Your work is submitted regardless of whether errors were found or not, but you are free to fix any errors and submit again before the due date.

In case of any problems, please contact the instructor or the TAs.


Written: 6 September 2017, Montek Singh, montek@cs.unc.edu