You are on page 1of 8

Qatar University College of Engineering Dept.

of Computer Science & Engg

Computer Programming GENG106 Lab Handbook Fall 2012Semester

Lab2: Expressions and Interactivity Arithmetic Expressions, Built-in Functions and Files
Objectives
At the end of this lab, you should be able to: Write C++ programs that solve simple arithmetic calculations Practice operators' priorities Use built-in math functions Write data to files using ofstream Read data from files using ifstream

Quick Review
Operator + * / %

Operation Addition Subtraction Multiplication Division Modulus

Example (a=14,b=4) a+b=18 a-b=10 a*b=56 a/b=3 (integer division if both a and b integers) a/b=3.5 (if a or b is float or double) a%b=2 ( reminder of 14/4)

A stream is a general name given to a flow of data. In C++ a stream is represented by an object of a particular class. Examples of stream objects familiar to us are cin and cout. Different streams are used to represent different kinds of data flow.

1 1 1 0 11110000101010001010 10010100010100011111 00001010100010101000 10101000101010001111 0 11110000101010001010 10010100010100011111 00001010100010101000 10101000101010001111

1 1 1 0 0

To program

From Program

Input stream

Output stream

Working with disk files requires another set of streams (classes): ifstream for input, fstream for both input and output, and ofstream for output. These streams are declared in the fstream file. Include it in your program using #include <fstream>

In formatted I/O, numbers are stored on disk as a series of characters. Thus 6.02, for example, is stored as the characters '6', '. ', '0', and '2'. Characters and strings are stored more or less normally. To open a file for output create an ofstream object, e.g. ofstream outfile("fdata.txt"); To send output to the file use the ofstream object, e.g. outfile<<"Hello world\n"; To open a file for input create an ifstream object: e.g. ifstream infile("fdata.txt"); To read from the file use the ifstream object, e.g. infile>>message; When you finish working with the file, terminate the connection, e.g. outfile.close();

1) The following program is intended to calculate the result of the following formula:

#include <iostream> using namespace std; int main() { double y,x,m,b,n; cout<<"Enter x: "; cin>>x; cout<<"Enter m: "; cin>>m; cout<<"Enter b: "; cin>>b; cout<<"Enter n: "; cin>>n; y=m*x+b/n; cout<<"y="<<y<<endl; return 0; } Run the program and enter the following values: x=2, m=3, b=5 and n=3. Write down the output of the program: ___________ Calculate the result manually using the values given above. Write down your answer: ________ If the program output is not correct, modify the program in order to calculate y correctly. According to their execution priorities in C++,order the following operators: +, / , * , %, () and -: 1) ________________ 2) ________________ 3) ________________

2) Write a program that will read two values double numbers calculate the values of the following: Hint: Use the pow() function Hint: To convert

and

from the keyboard and then

to radians multiply it by

. Use = 3.14159

Output the results of and on the screen. Hint: You have to use the cmath library; consult the Library Reference panel in www.cplusplus.com to explore how to use the sin() and pow() functions. 3) Write a program that asks the user to type in a time in seconds and display it in the standard format hours:minutes:seconds (where 1 hour = 3600 seconds and 1 minute = 60 seconds). Your output should look similar to this:

4) The midpoint of the line joining two points A(x1, y1) and B(x2, y2) is the two points is and the between .

Write a C++ program that asks the user to enter the coordinates of the end points of a straight line and then output the coordinates of its midpoint together with the distance between the two points.. Test your program using the coordinates of the following line:

5) The power, P, dissipated in a resistor of resistance R when a current i flows throw it is given by P=i2R. Write a C++ program that reads the resistance R (in ohms), i (in amps) and then outputs P.

6) Write a C++ program to read three numbers , and that represent the coefficients of the 2 quadratic equation + + =0, and then calculate and print its roots (i.e. the points where the curve cuts the x-axis) 1 and 2 which are found using the formula:

Use your program to calculate the roots of the equations represented by the following two curves. Make sure that your results match the values obtained graphically.
y = x2 - 5x + 6 y = 2x2 x 3

Now, can you use your program to solve x2+x+1=0? .. (Yes/No) If the answer is No; is it because of an error in your program? Or is it because the equation doesnt have real roots? . How can you fix your program to avoid passing a negative value to the sqrt()function?

7) Writing data/output to a file:

Save the following program and then run it:


#include<iostream> #include<string> #include<fstream> using namespace std; int main() { char ch='X'; int j=77; double d=6.02; string str1="Computer"; string str2="Programming";
ofstream outfile; outfile.open("fdata.txt");

outfile << endl << ch<<'\t'<<j<<'\t'<<d<<'\t'<<str1<<' '<<str2; outfile.close(); cout << "file written\n"; return 0; }

Describe the output of the above program. __________________________________________________________________________ __________________________________________________________________________

In which folder is fdata.txt saved? ___________________________________________ Which operator is used to send output to the file? ___________________________________ Modify the program so that the output is saved in the root folder of the C:\ drive. (Note that you have to use a double backslashes \\ to separate folders. Why?). Consider the outfile objet: What would happen if the fdata.txt file does not exist? ________________ ________________________________________________________________ What would happen if the fdata.txt file already exists? ________________ ________________________________________________________________ How can you append new data to an existing file? ________________________ ________________________________________________________________ Run the program again and open fdata.txt where youll see the same line twice.

8) Reading data from a file: Save the following program and then run it:
#include <fstream> #include <iostream> #include <string> using namespace std; int main(){ char ch; int j; double d; string str1, str2;
ifstream infile; infile.open("fdata.txt");

infile >> ch >> j >> d >> str1 >> str2; cout << ch<<" "<<j<<" "<<d<<" "<<str1<<" "<<str2<<endl; infile.close(); return 0; }

Describe the output of the above program. ___________________________________________________________________________

Which operator is used to read data from the file? ___________________________________ Consider the infile object: o What would happen if the fdata.txt file does not exist? __________________________ o What would happen if the fdata.txt file already exists? __________________________

9) In this exercise you will write two programs: Program 1: Write a program that asks the user to enter five floating-point numbers. The program should create a file and save (i.e. write) all five numbers to the file. Sample output

Output written to file numbersFile.txt

Program 2: Write a program that opens the file created by Program 1, reads the five numbers, and displays them. The program should also calculate and display the sum of the five numbers. Program screen output

Additional Exercises 10) The polar coordinates of a point P(x,y) are r . Tip: Use atan() from the cmath library Write a C++ program that asks the user to enter the Cartesian coordinates (x and y) of a point and then print the equivalent polar coordinates of that point in the format ( , ). (Make sure that the angle is displayed in degrees). Test your program using values from the following graph: or simply (r, ), where and

11) The sine rule states that in any triangle ABC:

where , and are the sides opposite to the angles A, B and C respectively. Write a C++ program that reads two angles; say A and B, of a triangle and the side between them, say c. Then let your program calculate and output the other two sides and the third angle. Run your program and enter the values based on the figure below: Tip: Remember that angles of a triangle add up to 180. 6

12) The cosine rule states that in any triangle ABC

where a, b and c are the sides opposite to the angles A, B and C respectively. An engineer is making a triangular component from a steel sheet with the dimensions shown in the figure below. He wants to calculate the length of the side AC for the following values of angle B: 80o, 95o and 105o. Write a C++ program that will help this engineer by printing each value of angle B and the corresponding value of the side AC.

13) To calculate the flow rate; of a liquid flowing in a pipe, a Venturi meter is used (see figure on the right). The cross-sectional area of the unrestricted pipe is and that of the throat (i.e. the restricted part) is . The flow rate is found from:

where is the difference in height and is constant.

is the acceleration due to gravity (9.81 m/sec2), which

Write a C++ program that reads r1 and r2 (the radii of the unrestricted pipe and the throat) and the difference in height, , and then output the flow rate, .