45 views

Uploaded by Wassen Hejjawi

computer programming

- Land Surveying Chapter 1 Introduction to Surveying
- Trig Function
- High Dive Summary
- geo_2_3
- calculus&combnatorcs.pdf
- 2
- 2015 10 Sp Mathematics Sa1 Solved 04.PDF New
- Electrical Formulas
- CDS Coaching In Chandigarh
- Question Paper_1-(3-3-2009)
- TA Comm Advt 050517 - For Online
- FBO Syllabus
- tspsc-forestbeatofficer-2017syllabus
- maths-class-x-sample-paper-02-for-board-exam-2019.pdf
- Cds Syllabus
- 96482360-TCS-2012-1(2)
- Objective_Ch_12_FSC_part1.pdf
- INMO_2018_solutions.pdf
- MBA Questions
- 1º Exam IV Bim Bimestral - Honradez

You are on page 1of 8

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 + * / %

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 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

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?

#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; }

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; }

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

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

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

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:

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, .

- Land Surveying Chapter 1 Introduction to SurveyingUploaded byAzrul Zulwali
- Trig FunctionUploaded byedurite_team
- High Dive SummaryUploaded bysoadquake981
- geo_2_3Uploaded byrmullen82
- calculus&combnatorcs.pdfUploaded byssshhhki
- 2Uploaded byoutlawman1892
- 2015 10 Sp Mathematics Sa1 Solved 04.PDF NewUploaded byAkshay Sharma
- Electrical FormulasUploaded byshabbir2025
- CDS Coaching In ChandigarhUploaded byDilpreet Rupal
- Question Paper_1-(3-3-2009)Uploaded bySatyendra Dubey
- TA Comm Advt 050517 - For OnlineUploaded bySunny Sharma
- FBO SyllabusUploaded byFhu
- tspsc-forestbeatofficer-2017syllabusUploaded byvijaykannamalla
- maths-class-x-sample-paper-02-for-board-exam-2019.pdfUploaded byApex Institute
- Cds SyllabusUploaded byKunal Aggarwal
- 96482360-TCS-2012-1(2)Uploaded byArtika Shrivastava
- Objective_Ch_12_FSC_part1.pdfUploaded byMuaaz Iqbal
- INMO_2018_solutions.pdfUploaded byShreesh Kumar
- MBA QuestionsUploaded byEamonn McHugh
- 1º Exam IV Bim Bimestral - HonradezUploaded byGaryAngeloChingayGonzales
- Escaleras - Stair Building CalculationsUploaded byJosé Pedro Casagrande Trentín
- 379081648-may-2018-solutions-ex.pdfUploaded byAnderson Alfred
- Maths With Out Coursework (2012)Uploaded byVishal Jalan
- jeopardy bubbled2Uploaded byapi-237499760
- Maths_Assgn_3_09_X (1).docUploaded byAnupam Pandey
- c ++ tip qaUploaded byFairoz Shaik
- Ib2 Math Studies 2nd Term Paper 2 MsUploaded byJun Mendoza
- 53626849 Drawing First YearUploaded byfree026
- Maths IGCSEUploaded byPhelix_Young_6404
- Samuel L. Greitzer - International Mathematical Olympiads 1959-1977Uploaded byLondres des

- ch07_01Uploaded byWassen Hejjawi
- CENG 106 Lab9Uploaded byWassen Hejjawi
- Question 1 business hw.docxUploaded byWassen Hejjawi
- business hw.docxUploaded byWassen Hejjawi
- Question 1 business hw.docxUploaded byWassen Hejjawi
- Wastes in Class - InterviewsUploaded byWassen Hejjawi
- About at RiskUploaded byWassen Hejjawi
- CENG 106 Lab7Uploaded byWassen Hejjawi
- Krajewski 9thUploaded bySubrata Halder
- CENG 106 Lab8Uploaded byWassen Hejjawi
- Wastes in Class - InterviewsUploaded byWassen Hejjawi
- CENG 106 Lab6.pdfUploaded byWassen Hejjawi
- Student Workload GuidelinesUploaded byWassen Hejjawi
- Question 3 Business HwUploaded byWassen Hejjawi
- Comments on WebsiteUploaded byWassen Hejjawi
- Shaikh Ahmad Bin Ali AlThaniUploaded byWassen Hejjawi
- Productio Operations Planning_aggregate Planning - Chapter3Uploaded byAlessandro Nájeraa
- Linear ProgrammingUploaded byMandy Chen
- Numerical Methods Lab 3Uploaded byWassen Hejjawi
- Formulation lp 3423Uploaded bymazin903
- Chap 8Uploaded byNikhil Dedhia
- (Layout)Uploaded byWassen Hejjawi
- notes7Uploaded byAbhishek Sarkar
- SQC-Lab1Uploaded byWassen Hejjawi
- Sample Mid1Uploaded byWassen Hejjawi
- min x11Uploaded byWassen Hejjawi
- TP1 FormulationUploaded byWassen Hejjawi
- TP1 FormulationUploaded byWassen Hejjawi
- hr annaUploaded byWassen Hejjawi
- TER201E_2011-12_F_midterm2_soltnUploaded byWassen Hejjawi

- scsUploaded byMahender Kandukuri
- Errors and Approximations PDFUploaded byMelissa
- Human NatureUploaded byFateme Gh
- Math Gk m1 Full ModuleUploaded byRivka Share
- The Curl OperatorUploaded byHoang Nguyen
- Worksheet FunctionsUploaded bylian
- Movement and Man at the end of the random walkUploaded byAttilio Sacripanti
- EditorialUploaded byq234234234
- Chapter-5Uploaded bySimiYadav
- Discrete and Continuous Probability Distributions PPT @ BEC DOMSUploaded byBabasab Patil (Karrisatte)
- Rtqalg2 FinalUploaded bydpool2002
- exp00_EA_Error Analysis.pdfUploaded byUtkarsh Agarwal
- General Mathematics Midterm ABM STEMUploaded byRPONTEJO
- Redundant-Radix-4-Arithmetic-Coprocessor-Design-Using-Vhdl.pdfUploaded byIJSTR Research Publication
- Moving Average Method Maths PptUploaded byAbhishek Mahto
- Trigonometry Ratios in Right TriangleUploaded byAlby
- 11304_tocUploaded bySudharsanViki
- Problem Set 2 SolUploaded bysristisagar
- 04 Numbers2 TOCUploaded byAnonymous OBPVTEuQL
- Soft ComputingUploaded byDiego Paez
- ch4_newUploaded bySaikat Saha
- Drawing.docxUploaded byBipin Karki
- Computational Complexity - Christos Papadimitriou.pdfUploaded byf
- Chapter 01 IntroductionUploaded byTina Philip
- Combinatorial EnumerationUploaded byKiran Kumar Kuppa
- Bayesian Inference Data Evaluation and Decisions Second EditionUploaded byCavallo Codardo
- Math+BasicsUploaded byabc
- Plane and Spherical TrigonometryUploaded byrex tanong
- HW1-previewUploaded byDan Devlin
- economicsUploaded byMad Madhavi