2 – Writing simple programs with input and output

advertisement

College of Engineering and Computer Science

Computer Science Department

Computer Science 106

Computing in Engineering and Science

Spring 2006 Class number 11672 Instructor: Larry Caretto

Second Programming Exercise

Objective

This exercise gives you practice in writing simple C++ programs. It should familiarize you with the basic structure that you need to use for all your C++ programs as well as the basic approaches for getting output to the screen and getting input from the keyboard.

Background for exercise

From the first exercise, you should be familiar with the basic structure of a simple C++ program shown below.

{

}

#include <iostream> using namespace std; int main()

// program statements go here return EXIT_SUCCESS;

You will use this basic structure for all your C++ programs. The purpose of each statement in this basis structure is described below.

The #include <iostream> statement is used to include the library routines for keyboard input and screen output. Other libraries, which you will see in future programs, may be included by additional #include statements. In the first exercise we included the <cmath> library to use standard math routines. Later in the course we will be using the libraries <fstream> , <iomanip> , and <string> , for file input-output, input-output formatting, and string variables, respectively.

The using namespace std; command allows us to use all the standard C++ names.

The concept of namespaces and variable scope will be discussed later in the course. For now, just take this statement as a requirement.

The statement int main() is the header for the function main. All C++ programs start execution in this function. Most of the programs that you write in this course will have only this one function. Later in the course, you will see how to write a program that is composed of several functions.

In the line, // program statements go here , the double slash (//) represents a comment. Such statements are ignored by the compiler and allow the programmer to place comments in the code that help a reader understand what is happening in the code.

The statement, return EXIT_SUCCESS; , indicates that the program is halting after a successful execution. We will later learn that C++ functions use the return statement to return control and (optionally) to transmit a value to the function that called it. The main function returns a value to the operating system so that operating-system programs that call a sequence of C++ programs can test the success or failure of a given program. The

Jacaranda (Engineering) 3333

E-mail: lcaretto@csun.edu

Mail Code

8348

Phone: 818.677.6448

Fax: 818.677.7062

Second programming exercise Comp 106, L. S. Caretto, Spring 2006 Page 2 quantity EXIT_SUCCESS is a global constant defined in the namespace std. We will later use global constant EXIT_FAILURE to terminate a program that does not execute successfully. The value of EXIT_SUCCESS is zero and you can simply write return 0; at the end of the program.

In addition to this basic program structure, you should include comment statements at the start of the program to describe its purpose and other information such as the programmer’s name and the date the program was written. See exercise one for examples of such comments.

In this exercise, you will use the basic structure to write a number of simple C++ programs. You can simply replace the line, // program statements go here , by the commands that you need.

Keyboard input and screen output in C++

Use the cout command with the output operator (sometimes called the insertion operator, <<) for screen output and the cin command with the input operator (sometimes called the extraction operator, >>) for keyboard input. Here some basic rules.

A single cout command can have one or more output (<<) operators to output one or more items to the screen.

 The command cout << “ <string>” ; will write the string between the quotation marks to the screen. E.g., cout << “My name is”; will write My name is to the screen.

The command cout << x;, where x is a variable, will write the value of the variable to the screen. E.g., the statements int x = 2; cout << x; will write 2 to the screen.

User input is almost always preceded by a cout command instructing the user on what to input. E.g., cout << “Enter a current in milliamps between 0.1 and 10:

“; cin << current;

You can enter several variables with a single cin command. Separate your entries by a space (or the enter key) and press the enter key after you enter the last data item. E.g., cout << “Enter x, y, and z: “; cin >> x >> y >> z; if you entered 3.2 5.1

16 and then pressed the enter key you would set x = 3.2, y = 5.1, and z = 16.

The cout command does not provide any spacing between output values. You must provide this yourself. You can provide space by outputting a blank string, a series of blanks surrounded by quotation marks. You can also use special characters \t or \n to insert a tab or to start a new line, respectively. The four letters endl (short for endline) inserted in an output stream also move the output to a new line. For example, if x = 13.2 and y = 0.123, the output results from various cout commands are shown in the table below.

Output command cout << x << y; cout << x << “ “ << y; cout << x << “\t“ << y; cout “x = “ << x << “ and y = “ << y; cout “x = “ << x << “\ny = “ << y; cout “x = “ << x << endl << y = “ << y;

Screen Output

13.20.123

12.2 0.123

12.2 0.123 x = 13.2 and y = 0.123 x = 13.2 y = 0.123

Preparing the file to submit for this exercise

This exercise has five tasks, which are slight variations of the same program. This paragraph will describe how you can create a single file, called the submission file, to which you will copy all your listings and all your results.

Second programming exercise Comp 106, L. S. Caretto, Spring 2006 Page 3

You should define a new project for this exercise. You can use the same program name (and project name) for all the tasks listed here. Follow the procedure that you learned in the first session to create a project and a C++ source file for the project. Just edit and reuse the single source file that is included in your project for all the tasks assigned here.

The following instructions will tell you how to prepare a submission file . This is a text file that contains all the information that you have to turn in for this exercise. You will create this file at the start of your session and copy results from the source code listing and the output screen to this file. When you are finished you will have a single file that you can print and turn in or submit by email. You will be using this process for all the remaining laboratory assignments.

To create the submission file, start with the Project menu and select Add New Item from this menu. This command will open a file selection dialog box that you have used to create a C++ file. Here you will use it to create a blank text file. Choose the Visual C++ folder in the

Catagories: menu in the upper left of the dialog and choose Text File (.txt) from the Templates: menu in the upper right. (You may have to use the slider in this menu to find this selection.)

Enter the file name in the next to last text box near the bottom (to the right of the word Name: ).

(Pick a name like pex2.txt; note thet the .txt extension is automatically added.) Each task below will give you specific instructions about what you should place in this submission file.

There are several ways to place information into this submission file: (1) you can type onto this file, for example to write your name and the name of the assignment; (2) you can copy code from source files to this file using the copy and paste commands; (3) you can copy screen output (see instructions below) to this file. Start by typing your name and the laboratory date at the top of this file. You should also type a line on the submission file indicating the start of each new task. You can have both the submission file and the C++ source open at the same time in the IDE. You can select the file that you want to edit by clicking the various tabs above the editing region. (You can also select the file from the Window menu.)

See the example submission file in the “Submission Requirements” section at the end of these notes.

Copying the screen

You can copy the results from the display screen to a file by the following steps.

Use the mouse to place the arrow in colored band at the top of the display screen.

Right click the mouse button to display the menu for the display screen.

Select Edit from the main menu and Mark from the edit submenu. At this point, there will be a flashing block cursor in the upper-left-hand corner of the display screen.

Use the mouse to select the text that you want to copy. Hit the enter key after you have selected the text.

Move to the file where you want to paste the copied text, place the cursor at the correct location in that file and execute the paste command by menu, icon or a control-V keystroke.

You can use this technique for any programming exercise, assignment or quiz.

Programming tasks

Some of the input data that you are asked to enter will produce incorrect results such as a division by zero. These bad data specifications are intended to show you the results of incorrect data entry.

Second programming exercise Comp 106, L. S. Caretto, Spring 2006 Page 4

Task one: Simple input and output with type double – copy and compile the following code.

{

#include <iostream> using namespace std; int main() double x, y, z; cout << "Enter a value for x: "; cin >> x; cout << "Enter a value for y: "; cin >> y; z = x / y; cout << "For x = " << x << " and y = " << y

<< ", x / y = " << z << "\n\n"; return EXIT_SUCCESS;

}

Execute the code for the following input pairs: (1) x = 1, y = 2, (2) x = 1, y = 0, (3) x = 1, y = 3;

(4) x = 10 -6 , y = 10 6 , (5) x = 6, y = 3, (6) x = 6, y = 4. Copy the code and all output from the screen to the submission file. Note that a number like 5.6x10

-6 can be entered as 5.6E-6. The number 10 -6 , which is really shorthand for 1x10 -6 should be entered as 1E-6. Similarly, the input for 10 6 would be 1E6. (You could also enter 10 -6 and 10 6 as, respectively, 0.000001 and

1000000.)

Task two: Simple input and output with type int – modify the code so that the first statement is reads int x, y, z; compile the code and repeat the execution with the input values shown above. Copy the code and all output to the submission file. Make sure that you understand why the results from this task are different from those in task one.

Task three: Alternative input approach – modify the code in task two so that the user sees a single input prompt asking the user values for x and y. The user should then enter two values.

Run this program for a single pair of input values. Copy the code and the output to the submission file

Task four: Output spacing – remove the statement in the code in task three that prints the results to the screen. (Do not change or remove the input prompt.) Use the following statement in place of the deleted results-output statement: cout << x <<y << z; run this program for x = 8 and y = 4; copy the code and the screen to the submission file. Fix the new output statement so that there is spacing between the numbers on the output. After you make the correction, run the program for the same input values. Once you have the result you want, copy the modified code and the screen output to the submission file.

Task five: Still more output spacing – modify the output statement in the code from task four so that the screen looks like the following when you are done (place your name and t oday’s date in the second output line):

Results for programming exercise 2:

Larry Caretto February 9, 2006

Input value of x = 10

Input value of y = 3

Output value of z = x / y = 3.33333

Press any key to continue

Second programming exercise Comp 106, L. S. Caretto, Spring 2006 Page 5

In particular, the output has the following features: (1) there is a blank line after the title line, the name line, and the line with the value of z; (2) the final equal signs in the last three lines are in the same column, (3) the last line starts two spaces to the left of the title line and the name line, and

(4) the end of the date line is aligned with the end of the line for the output value. Copy the code for this task and the output screen to the submission file. HINT: It is easier to use spaces than the “\t” tab spacing.

Submission requirements

Due Date: February 9.

Submit a copy of your submission file with the elements specified above. Make sure that your name is at the top of your submission file. Edit the submission file to show where one task ends and the other begins. Here is a sample of what your submission file should look like.

Sample submission file for exercise two

Larry Caretto Comp 106

Submitted February 9, 2006

Task one code

#include <iostream> using namespace std; int main()

{ double x, y, z; cout << "Enter a value for x: "; cin >> x; cout << "Enter a value for y: "; cin >> y; z = x / y; cout << "For x = " << x << " and y = " << y

<< ", x / y = " << z << "\n\n"; return EXIT_SUCCESS;

}

Task one output, first input data set

Enter a value for x: 3

Enter a value for y: 9

For x = 3 and y = 9, x / y = 0.333333

Task one output, second input data set

Enter a value for x: 5

Enter a value for y: 3

For x = 5 and y = 3, x / y = 1.66667

Remaining task one output not shown

Task two code

Task two code not shown

Task two output, first input data set

Second programming exercise Comp 106, L. S. Caretto, Spring 2006 Page 6

Enter a value for x: 3

Enter a value for y: 9

For x = 3 and y = 9, x / y = 0

Task two output, second input data set

Enter a value for x: 5

Enter a value for y: 3

For x = 5 and y = 3, x / y = 1

Remainder of file not shown

Submit a printed listing or send an email to lcaretto@csun.edu with your listings before 11:59 pm on the due date. Please make only one submission, either written or email. Your submission file should include the following items

Task one code

Task one output for six cases

Task two code

Task two output for six cases

Task three code

Task three output

Original task four code

Original task four output

Modified task four code

Modified task four output

Task five code

Task five output

Download