1 CS102 Introduction to Computer Programming Week 3 Chapter 3 Expressions and Interactivity.

Slides:



Advertisements
Similar presentations
CS1 Lesson 3 Expressions and Interactivity CS1 -- John Cole1.
Advertisements

1 9/13/06CS150 Introduction to Computer Science 1 Type Casting.
1 Objectives Understand streamed input and output.
Starting Out with C++, 3 rd Edition 1 Chapter 3. Expressions and Interactivity.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
1 9/17/07CS150 Introduction to Computer Science 1 Type Casting.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 3 Expressions.
CS150 Introduction to Computer Science 1
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 1.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. WAB rev 2 Starting Out with C++ Early Objects Sixth Edition by Tony Gaddis,
1 9/08/06CS150 Introduction to Computer Science 1 Arithmetic Operators.
1 Chapter 3 Expressions and Interactivity. 2 Topics 3.1 The cin Object 3.2 Mathematical Expressions 3.3 When You Mix Apples and Oranges: Type Conversion.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Chapter 3: Input/Output
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Chapter 3 Expressions and Interactivity Department of Computer Science Missouri State Univeristy.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Expressions and Interactivity.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
Lecture 6: Expressions and Interactivity (Part II) Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 3: Expressions & Interactivity
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for CMPS 1043 Computer Science I at MSU.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
C++ Programming, Namiq Sultan1 Chapter 3 Expressions and Interactivity Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 3 Expressions and Interactivity.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Expressions and Interactivity. 3.1 The cin Object.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Formatting Output.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 3: Expressions and Interactivity.
CMPSC 121- Spring 2015 Lecture 6 January 23, 2015.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
2/4/2016Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Last Time…. Operators Arithmetic Operators Assignment Operators Increment/Decrement Operators Relational Operators Logical Operators Expression Statements.
Math Operators and Output Formatting. Incrementing and Decrementing StatementEquivalent Counter++;Counter = Counter + 1; ++Counter;Counter = Counter +
Chapter Expressions and Interactivity 3. The cin Object 3.1.
Chapter 4: Introduction To C++ (Part 3). The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3: Expressions and Interactivity.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Lecture 3 Expressions, Type Conversion, Math and String
Today Variable declaration Mathematical Operators Input and Output Lab
CS102 Introduction to Computer Programming
Chapter 3. Expressions and Interactivity
Chapter 3: Expressions and Interactivity.
Chapter 3: Expressions and Interactivity
Input and Output Chapter 3.
Expressions and Interactivity
Starting Out with C++: From Control Structures through Objects
Expressions and Interactivity
Chapter 3 Input output.
Standard Version of Starting Out with C++, 4th Edition
C++ for Engineers and Scientists Second Edition
Lecture 3 Expressions, Type Conversion, and string
Presentation transcript:

1 CS102 Introduction to Computer Programming Week 3 Chapter 3 Expressions and Interactivity

2 Chapter 3 Expressions and Interactivity The cin object Mathematical Expressions Automatic conversion and promotion Overflow and underflow The typecast operator The power of constants Multiple assignments Combined assignment operators Formatting output with stream manipulators Formatted input More mathematical library functions

3 The cin Object cin is the standard input object –Causes the program to wait until information is typed at the keyboard and the enter key is pressed –Automatically converts the data read to the type of the variable used to store it –Truncates floating point numbers that are to be stored in integer variables Notice the >> and << operators appear to point in the direction information is flowing. Concept - The cin object reads information typed at the keyboard

4 Program 3-1 #include void main(void)‏ { int Length, Width, Area; cout <<"This program calculates the"; cout <<" area of a rectangle.\n"; cout <<"What is the length of the "; cout <<" rectangle? "; cin >>Length; cout <<"What is the width of the"; cout <<" rectangle? "; cin>>Width; Area = Length * Width; cout <<"The area of the rectangle is " cout << Area << ".\n"; } Program Output This program calculates the area of a rectangle. What is the length of the rectangle? 10 [Enter] What is the width of the rectangle? 20 [Enter] The area of the rectangle is 200. This program will calculate the area of any rectangle

5 Program 3-2 /*This program reads the length and width of a rectangle. It calculates the rectangle's area and displays the value on the screen. */ #include void main(void)‏ { int Length, Width, Area; cin >> Length; cin >> Width; Area = Length * Width; cout << "The area of the rectangle is " << Area << endl; } Program Output 10 [Enter] 20 [Enter] The area of the rectangle is 200. This program does not let the user know what is needed as input.

6 The cin Object Multiple values are separated by spaces The Variables are assigned values in the order they are entered. cin can read character strings into a properly defined variable –If the input string is too large, adjacent memory can be corrupted –Don't forget to leave room for the null character –The string can not contain spaces Concept - The cin object can gather multiple values at once

7 Program 3-3 #include void main(void)‏ { int Length, Width, Area; cout <<"This program calculates"; cout <<" the area of a rectangle.\n"; cout <<"Enter the length and width"; cout <<" of the rectangle separated"; cout <<" by a space. \n"; cin >> Length >> Width; Area = Length * Width; cout <<"The area of the rectangle is "; cout << Area << endl; } Program Output This program calculates the area of a rectangle. Enter the length and width of the rectangle separated by a space [Enter] The area of the rectangle is 200 This program accepts multiple entries on one line

8 Program 3-4 or 3-3 version 4 /*This program demonstrates how cin can read multiple values of different data types. */ #include void main(void)‏ { int Whole; float Fractional; char Letter; cout << "Enter an integer, a float, "; cout << "and a character: "; cin >> Whole >> Fractional >> Letter; cout << "Whole: " << Whole << endl; cout << "Fractional: " << Fractional << endl; cout << "Letter: " << Letter << endl; } Program Output Enter an integer, a float, and a character: b [Enter] Whole: 4 Fractional: 5.7 Letter: b Values of different data types can be entered on the same line. They must be entered in the correct order

9 Program 3-5 or 3-4 version 4 Program Output What is your name? Charlie [Enter] Good morning Charlie // This program demonstrates how cin can read a string into a character array. */ #include void main(void)‏ { char Name[21]; cout << "What is your name? "; cin >> Name; cout << "Good morning "; cout << Name << endl; } cin can read strings as well as numbers. Strings are stored in character arrays.

10 Program 3-6 or 3-5 version 4 //This program reads two strings //into two character arrays. #include void main(void)‏ { char First[16], Last[16]; cout << "Enter your first and last"; cout << " names and I will\n"; cout << "reverse them.\n"; cin >> First >> Last; cout << Last << ", " << First; cout <<endl; } Program Output Enter your first and last names and I will reverse them. Johnny Jones [Enter] Jones, Johnny Note that a space is used to separate the two inputs. If you want to read in a string with embedded spaces you can not use the cin command

11 Notes on strings: If a character array is intended to hold strings, it must be at least one character larger than the largest string that will be stored in it. The cin object will let the user enter a string larger than the array can hold. If this happens, the string will overflow the array’s boundaries and destroy other information in memory. If you wish the user to enter a string that has spaces in it, you cannot use this input method.

What header file must be included in programs using cin? 3.2 What type of variable is used to hold a C-string? 3.3 Write a declaration statement for a character array named customer. It should be large enough to hold 52 characters in length. 3.4 T or F: cin requires the user to press the [Enter] key when finished entering data 3.5 Assume value is an integer variable. If the user enters 3.14 in response to the following programming statement, What will be stored in value cin >> value; A.3.14 B.3 C.0 D.Nothing, an error message is displayed Check point 3.1 char char customer[53];

13 Mathematical Expressions A mathematical expression is a programming statement that has a value Consists of operators and their operands –operands can be constants or variables Can be used by the cout object to display the value of the expression. cout << (Operand1 operator Operand2); Concept - C++ allows you to construct complex mathematical expressions using multiple operators and grouping symbols

14 Program 3-7 or 3-6 version 4 /* This program asks the user top enter the numerator and denominator of a fraction and it displays the decimal value*/ void main(void)‏ { float Numerator, Denominator; cout << "This program shows the "; cout << "decimal value of a fraction.\n"; cout << "Enter the numerator: "; cin >> Numerator; cout << "Enter the denominator: "; cin >> Denominator; cout << "The decimal value is "; cout << (Numerator / Denominator); } Program Output This program shows the decimal value of a fraction. Enter the numerator: 3 [Enter] Enter the denominator: 16 [Enter] The decimal value is Mathematical expressions can be used in cout statements. Note the inputs are integers but they are converted to floats for storage

15 Precedence If two operators share an operand the one with the highest precedence works first highest- (Unary negation)‏ */% Lowest+- Example6 * = 39 (not 24)‏ Example / 3 = 7 (not 5 )‏ Mathematical expressions are evaluated left to right

16 Associativity Associativity is either left to right or right to left If two operators sharing an operand have the same precedence, they work according to their Associativity. Right to left- (Unary negation)‏ left to right*/% left to right +- Associativity is the order in which an operator works with its operands

17 Grouping With Parentheses Parentheses are used to force some operations to be performed before others –examples: (5+2)*4 = / (5-3) = 5 ( ) % 2 -1 = 0

18 No Exponents Please Include the following file in your program to deal with exponents: #include (or math.h, old way)‏ Use the pow function to raise a value (x) to the power (y) (x and y may be int or float)‏ example: the area of a circle is  (radius 2 )‏ Area = 3.14 * pow(radius,2); The pow function returns a double Concept - C++ does not have an operator to raise a number to a power. A library function must be used

19 Program 3-8 or 3-7 version 4 /*This program calculates the area of a circle. The formula for the radius of a circle is Pi times the radius squared Pi is */ #include void main(void)‏ { double Area, Radius; cout << "This program calculates the "; cout << " area of a circle.\n"; cout << "What is the radius of "; cout << "the circle? "; cin >> Radius; Area = * pow(Radius,2); cout << "The area is " << Area; } Program Output This program calculates the area of a circle. What is the radius of the circle? 10 [Enter] The area is This program uses the pow function to find the area of a circle

Write C++ expressions for the following algebraic expressions: y = 6x a = 2b + 4c y = x 2 x + 2 g = z Complete the table below by writing the value of each expression in the "Value" column. ExpressionValue * 5 12 / 2 – * 2 – % 3 – 1 (6 + 2 ) * 3 Check Point y = 6 * x; a = (2 * b ) + (4 * c ) ; y = pow( x,2); g = (x + 2) / pow( z,2);

When you Mix Apples and Oranges: Type Coercion Rules Concept - When an operator's operands are of different data types, C++ will automatically convert them to the same data type Rule 1 - Chars,shorts, and unsigned shorts are automatically promoted to int. Rule 2 - If two values are of different types the lower-ranking one is promoted to the type of the higher-ranking on Rule 3 - when the value of an expression is assigned to a variable it will be converted to the data type of the variable

Overflow and Underflow When a variable is assigned a value that is too large or too small in range for that variable’s data type, the variable overflows or underflows. –Overflow - when a variable is assigned a number that is too large for its data type –Underflow - when a variable is assigned a number that is too small for its data type

23 Overflow and Underflow If an integer variable overflows or underflows the value wraps back around –no warning or error message is generated If a floating point variable overflows or underflows the result depends on the compiler. Concept - When a variable is assigned a value that is too large or too small in range for that variables data type, the variable underflows or overflows

24 Program 3-9 or 3-8 version 4 //This program demonstrates integer overflow and underflow #include void main(void)‏ { short TestVar = 32767; cout << TestVar << endl; TestVar = TestVar + 1; cout << TestVar << endl; TestVar = TestVar - 1; cout << TestVar << endl; } Program Output This program assumes that an integer is stored in two bytes of memory

25 Program 3-10 or 3-9 version 4 //This program can be used to see // how your system handles floating // point overflow and underflow. #include void main(void)‏ { float Test; Test = 2.0e38 * 1000; // Should overflow Test cout << Test << endl; Test = 2.0e-38 / 2.0e38; // Should underflow Test cout << Test << endl; } Program Output 1.#INF 0 This compiler does not generate a runtime error but the value stored may not be usable

The Typecast Operator The typecast operator manually promotes or demotes a value –works on either an expression or a variable –the conversion is temporary –truncation may occur Example: Val = int(number); Val = float(digit1) / digit2; // prevents integer divide Val = float (digit1/digit2); // allows integer divide Val = (int) number; // is also correct

27 Program 3-11 or 3-10 version 4 #include void main(void)‏ { int Months, Books; float PerMonth; cout << "How many books do you "; cout << "plan to read? "; cin >> Books; cout << "How many months will "; cout << "it take you to read them? "; cin >> Months; PerMonth = float(Books) / Months; cout << "That is " << PerMonth cout << " books per month.\n"; Program Output How many books do you plan to read? 30 [Enter] How many months will it take you to read them? 7 [Enter] That is books per month. This program uses the type cast operator to avoid integer division

28 Typecast Warnings In Program 3-11, the following statement would still have resulted in integer division: PerMonth = float(Books / Months); Because the division is performed first and then the result is type cast to a float. Type casting has no effect on the values it operates on. A temporary variable is created for the duration of the instruction.

29 Program 3-12 or 3-11 version 4 /*This program uses a typecast operator to print a character from a number.*/ #include void main(void)‏ { int Number = 65; cout << Number << endl; cout << char(Number) << endl; } Program Output 65 A

30 The Power of Constants Makes the program more readable Simplifies maintenance Example: const float PI = ; or #define PI Using a named constant will not make the program run more efficiently Concept - Constants may be given names that symbolically represent them in a program

31 Program 3-13 or 3-12 version 4 #include void main(void)‏ { const float Pi = ; double Area, Radius; cout << "This program calculates"; cout << " the area of a circle.\n"; cout << "What is the radius of "; cout << " the circle? "; cin >> Radius; Area = Pi * pow(Radius,2); cout << "The area is " << Area; } Program Output This program calculates the area of a circle. What is the radius of the circle? 5 [Enter] The area is The literal has been replaced with a floating point constant.

32 The #define Directive The older C-style method of creating named constants is with the #define directive, although it is preferable to use the const modifier. #define PI is roughly the same as const float PI= ;

33 Program 3-14 or 3-13 version 4 #include // needed for pow function #define PI void main(void)‏ { double Area, Radius; cout << "This program calculates"; cout << " the area of a circle.\n"; cout << "What is the radius of the"; cout << " circle? "; cin >> Radius; Area = PI * pow(Radius, 2); cout << "The area is " << Area; } Program Output This program calculates the area of a circle. What is the radius of the circle? 5 [Enter] The area is Remember that the preprocessor performs a textual substitution. So each instance of Pi becomes a floating point literal.

34 Multiple Assignments Groups like-variables in one statement May be used within an expression –has the lowest precedence of all arithmetic operations –Should be placed within parentheses May be confusing if not clearly documented Example: a = b = c = d = 12 Concept - Multiple assignment means to assign the same value to several variables with one statement. /

35 Combined Assignment Operators Eliminates the need to enter the variable name twice OperatorExample usageEquivalent to +=x += 5;x = x + 5; -=y -=2;y = y - 2; *=z *= 10;z = z * 10; /=a /=b;a = a / b; %=c %= 3;c = c % 3; Concept - The combined assignment operators make common arithmetic operations easier

Formatting Output With String Manipulation setw(n) n = the width of the display setprecision(n) n = the number of significant digits or decimal places displayed flags: left right fixed Concept - The cout object provides ways to format data as it is being displayed. dec hex oct scientific showpoint showpos uppercase

37 Program 3-17 or 3-15 version 4 //This program displays three rows of numbers #include void main(void)‏ { int Num1 = 2897, Num2 = 5, Num3 = 837, Num4 = 34, Num5 = 7, Num6 = 1623, Num7 = 390, Num8 = 3456, Num9 = 12; // Display the first row of numbers cout << Num1 << " "; cout << Num2 << " "; cout << Num3 << endl; // Display the second row of numbers cout << Num4 << " "; cout << Num5 << " "; cout << Num6 << endl; // Display the third row of numbers cout << Num7 << " "; cout << Num8 << " "; cout << Num9 << endl; } Program Output This program displays values with no output formatting. There is no column alignment.

38 Program 3-18 or 3-16 version 4 /*This program displays three rows of numbers. */ #include void main(void)‏ { int Num1 = 2897, Num2 = 5, Num3 = 837, Num4 = 34, Num5 = 7, Num6 = 1623, Num7 = 390, Num8 = 3456, Num9 = 12; // Display the first row of numbers cout << setw(4) << Num1 << " "; cout << setw(4) << Num2 << " "; cout << setw(4) << Num3 << endl; // Display the second row of numbers cout << setw(4) << Num4 << " "; cout a<< setw(4) << Num5 << " "; cout << setw(4) << Num6 << endl; // Display the third row of numbers cout << setw(4) << Num7 << " "; cout << setw(4) << Num8 << " "; cout << setw(4) << Num9 << endl; } Program Output The setw command is used to line up the columns. The default is right justified

39 Program 3-19 or 3-17 version 4 /* This program demonstrates the setw manipulator being used with values of various data types. */ #include void main(void)‏ { int IntValue = 3928; float FloatValue = 91.5; char StringValue[14] = "John J. Smith"; cout << "(" << setw(5); cout << IntValue << ")" << endl; cout << "(" << setw(8); cout << FloatValue << ")" << endl; cout << "(" << setw(16); cout << StringValue << ")" << endl; } Program Output ( 3928)‏ ( 91.5)‏ ( John J. Smith)‏ setw can format the output of any data type

40 Precision Floating point values may be rounded to a number of significant digits, or precision, which is the total number of digits that appear before and after the decimal point.

41 Program 3-20 or 3-18 version 4 /*This program demonstrates how setprecision rounds floating point value. */ #include void main(void)‏ { float Quotient, Number1 = , Number2 = 26.91; Quotient = Number1 / Number2; cout << Quotient << endl; cout << setprecision(5) << Quotient << endl; cout << setprecision(4) << Quotient << endl; cout << setprecision(3) << Quotient << endl; cout << setprecision(2) << Quotient << endl; cout << setprecision(1) << Quotient << endl; } Program Output setprecision does not truncate numbers it rounds them up

42 Table 3-11 NumberManipulatorValue Displayed setprecision(3) setprecision(5) setprecision(4) setprecision(2)34 cout << fixed; setprecision(3) setprecision(5) setprecision(4) setprecision(2)34.29

43 Program 3-21 or 3-19 version 4 /* This program asks for sales figures for 3 days. The total sales is calculated and displayed in a table*/ #include Using namespace std; int main()‏ { float Day1, Day2, Day3, Total; cout << "Enter the sales for day 1: "; cin >> Day1; cout << "Enter the sales for day 2: "; cin >> Day2; cout << "Enter the sales for day 3: "; cin >> Day3; Total = Day1 + Day2 + Day3; cout << "\nSales Figures\n"; cout << " \n"; cout << setprecision(5); cout << "Day 1: " << setw(8) << Day1; cout << endl; cout << "Day 2: " << setw(8) << Day2; cout << endl; cout << "Day 3: " << setw(8) << Day3; cout << endl; cout << "Total: " << setw(8) << Total; cout << endl; return 0; } This program will display 5 significant digits. But what if the total takes 6

44 Program Output Enter the sales for day 1: [Enter] Enter the sales for day 2: [Enter] Enter the sales for day 3: [Enter] Sales Figures Day 1: Day 2: Day 3: Total: 1899 The value has been truncated

45 Program 3-22 or 3-20 version 4 #include using namespace std; int main()‏ { float Day1, Day2, Day3, Total; cout << "Enter the sales for day 1: "; cin >> Day1; cout << "Enter the sales for day 2: "; cin >> Day2; cout << "Enter the sales for day 3: "; cin >> Day3; Total = Day1 + Day2 + Day3; cout << "\nSales Figures\n"; cout << "------\n"; cout << setprecision(2) << fixed << showpoint; cout << "Day 1: " << setw(8) << Day1 << endl; cout << "Day 2: " << setw(8) << Day2 << endl; cout << "Day 3: " << setw(8) << Day3 << endl; cout << "Total: " << setw(8) << Total << endl; return 0; } Program Output (modified) Enter the sales for day 1: [Enter] Enter the sales for day 2: [Enter] Enter the sales for day 3: [Enter] Sales Figures Day 1: 321 Day 2: Day 3: Total: The decimal point is displayed only if there are digits to the right of it.

46 Stream Manipulator fixedDisplays floating-point numbers in fixed point notation. setw(n)Establishes a print field of n spaces. showpointCauses a decimal point and trailing zeros to be displayed, even if there is no fractional part. setprecision(n)Sets the precision of floating-point numbers leftCauses subsequent output to be left justified. rightCauses subsequent output to be right justified.

47 Important points about the way cin handles field widths: The field width only pertains to the very next item entered by the user. cin stops reading input when it encounters a whitespace character or when it has all the character it needs. –White space characters include the [Enter] key, space, and tab.

48 Program 3-28 or 3-22 version 4 //This program demonstrates cin's // getline member function. #include void main(void)‏ { char String[81]; cout << "Enter a sentence: "; cin.getline(String, 81); cout << "You entered "; cout << String << endl; } Program Output Enter a sentence: To be, or not to be. [Enter] You entered To be, or not to be. cin.getline will read one less character than the second parameter specifies to make room for the NULL character

49 Program 3-29 or 3-23 version 4 #include void main(void)‏ { char Ch; cout << "Type a character cout << " and press cout << " Enter: "; cin >> Ch; cout << "You entered " << Ch << endl; } Program Output Type a character and press Enter: A [Enter] You entered A cin requires that the user enter only a single. non white space character. All other input is ignored.

50 Program 3-30 or 3-23 version 4 #include void main(void)‏ { char Ch; cout << "This program has"; cout << " paused. Press"; cout << " enter to continue."; cin.get(Ch); cout << "Thank you!"; cout << endl; } Program Output This program has paused. Press Enter to continue. [Enter] Thank you! cin.get will accept any key, particularly the return key

51 Program 3-31 or 3-23? version 4 #include void main(void)‏ { char Ch; cout << "Type a character"; cout << " and press Enter: "; cin.get(Ch); cout << "You entered "; cout << Ch << endl; cout << "Its ASCII code is "; cout << int(Ch) << endl; } Program Output Type a character and press Enter: [Enter] You entered Its ASCII code is 10 cin.get will accept non printable and white space characters

52 Mixing cin and cin.get Mixing cin.get with cin can cause an annoying and hard-to-find problem. Pressing the [Enter] key after inputting a number will cause the newline character to be stored in the keyboard buffer. To avoid this, use cin.ignore: cin.ignore(20,’\n’); // will skip the next 20 chars in the input buffer or until a newline is encountered, whichever comes first cin.ignore(); //will skip the very next character in the input buffer

53 More Mathematical Library Functions abs Absolute Value exp e x fmod –modulus for floating point Concept - The C++ runtime library provides several functions for performing complex mathematical operations. log natural log log10 base 10 log sqrt square root cos cosine sin sine tan tangent

54 Table 3-14 or 3-13 version 4 abs y = abs(x); Returns the absolute value of the argument. The argument and the return value are integers. cos y = cos(x); Returns the cosine of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles. exp y = exp(x); Computes the exponential function of the argument, which is x. The return type and the argument are doubles.

55 Table 3-14 continued or 3-13 version 4 fmod y = fmod(x, z); Returns, as a double, the remainder of the first argument divided by the second argument. log y = log(x); Returns the natural logarithm of the argument. The return type and the argument are doubles. log10 y = log10(x); Returns the base-10 logarithm of the argument. The return type and the argument are doubles.

56 Table 3-14 continued or 3-13 version 4 sin y = sin(x); Returns the sine of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles. sqrt y = sqrt(x); Returns the square root of the argument. The return type and argument are doubles. tan y = tan(x); Returns the tangent of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles.

57 Program 3-32 or 3-24 version 4 #include #include // For sqrt void main(void)‏ { float A, B, C; cout << "Enter the length of side A: "; cin >> A; cout << "Enter the length of side B: "; cin >> B; C = sqrt(pow(A, 2.0) + pow(B, 2.0)); cout.precision(2); cout << "The length of the "; cout << "hypotenuse is "<< C << endl; } Program Output Enter the length of side A: 5.0 [Enter] Enter the length of side B: 12.0 [Enter] The length of the hypotenuse is 13 This program uses the sqrt function to find the hypotenuse of a right triangle

58 Random Numbers y = rand(); (from the stdlib.h library)‏ –returns pseudo-random number –C++ returns the same sequence of numbers each time the program executes srand(x); (from the stdlib.h library)‏ –seeds the random number generator so that a new sequence of numbers will be generated Concept - Some programming techniques require the use of randomly generated numbers

59 Program 3-33 or 3-25 version 4 // This program demonstrates random //numbers. #include void main(void)‏ { unsigned Seed; cout << "Enter a seed value: "; cin >> Seed; srand(Seed); cout << rand() << endl; } Program Output Enter a seed value: Program Output with Other Example Input Enter a seed value: It still gives the same numbers for the same seed value

60 Basic File I/O The file fstream.h contains all the declarations necessary for file operations #include It declares the following data types –ofstream used to open a file for output –ifstream used to open a file for input –fstream used to open a file for both input and output You must declare an object of one of these data types i.e ifstream InputFile;

61 Reading from a file Once the file has been opened you can read data from it similar to the way cin is used InputFile >> Variable_Name The data is read in the order found in the file You can create a file using notepad or any other word processor. Make sure the file name matches the file name in the open statement exactly The file must be in the same directory that the executable file is located or you will need to specify the exact path.