CS102 Introduction to Computer Programming - PowerPoint PPT Presentation

1 / 62
About This Presentation
Title:

CS102 Introduction to Computer Programming

Description:

CS102 Introduction to Computer Programming Week 3 Chapter 3 Expressions and Interactivity Chapter 3 Expressions and Interactivity The cin object Mathematical ... – PowerPoint PPT presentation

Number of Views:148
Avg rating:3.0/5.0
Slides: 63
Provided by: Enginee66
Category:

less

Transcript and Presenter's Notes

Title: CS102 Introduction to Computer Programming


1
CS102Introduction 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
(No Transcript)
4
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 gtgt and ltlt operators appear to point in
    the direction information is flowing.

Concept - The cin object reads information typed
at the keyboard
5
Program 3-1
This program will calculate the area of any
rectangle
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • int Length, Width, Area
  • cout ltlt"This program calculates the"
  • cout ltlt" area of a rectangle.\n"
  • cout ltlt"What is the length of the "
  • cout ltlt" rectangle? "
  • cin gtgtLength
  • cout ltlt"What is the width of the"
  • cout ltlt" rectangle? "
  • cingtgtWidth
  • Area Length Width
  • cout ltlt"The area of the rectangle is "
  • cout ltlt Area ltlt ".\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.

6
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 ltiostreamgt
  • using namespace std
  • void main()?
  • int Length, Width, Area
  • cin gtgt Length
  • cin gtgt Width
  • Area Length Width
  • cout ltlt "The area of the rectangle is " ltlt Area
    ltlt endl

This program does not let the user know what is
needed as input.
  • Program Output
  • 10 Enter
  • 20 Enter
  • The area of the rectangle is 200.

7
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
8
Program 3-3
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • int Length, Width, Area
  • cout ltlt"This program calculates"
  • cout ltlt" the area of a rectangle.\n"
  • cout ltlt"Enter the length and width"
  • cout ltlt" of the rectangle separated"
  • cout ltlt" by a space. \n"
  • cin gtgt Length gtgt Width
  • Area Length Width
  • cout ltlt"The area of the rectangle is "
  • cout ltlt Area ltlt endl

This program accepts multiple entries on one line
Program Output This program calculates the area
of a rectangle. Enter the length and width of the
rectangle separated by a space. 10 20 Enter The
area of the rectangle is 200
9
Program 3-4 or 3-3 version 4
  • / This program demonstrates how cin can read
    multiple values of different data types. /
  •  include ltiostreamgt
  •  using namespace std
  • void main()?
  • int Whole
  • float Fractional
  • char Letter
  •  
  • cout ltlt "Enter an integer, a float, "
  • cout ltlt "and a character "
  • cin gtgt Whole gtgt Fractional gtgt Letter
  • cout ltlt "Whole " ltlt Whole ltlt endl
  • cout ltlt "Fractional " ltlt Fractional ltlt endl
  • cout ltlt "Letter " ltlt Letter ltlt endl

Values of different data types can be entered on
the same line. They must be entered in the
correct order
Program Output Enter an integer, a float, and a
character 4 5.7 b Enter Whole 4 Fractional
5.7 Letter b
10
Program 3-5 or 3-4 version 4
  • // This program demonstrates how cin can read a
    string into a character array. /
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • char Name21
  • cout ltlt "What is your name? "
  • cin gtgt Name
  • cout ltlt "Good morning "
  • cout ltlt Name ltlt endl

cin can read strings as well as numbers. Strings
are stored in character arrays.
Program Output What is your name? Charlie
Enter Good morning Charlie
11
Program 3-6 or 3-5 version 4
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
  • // This program reads two strings
  • // into two character arrays.
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • char First16, Last16
  •   cout ltlt "Enter your first and last"
  • cout ltlt " names and I will\n"
  • cout ltlt "reverse them.\n"
  • cin gtgt First gtgt Last
  • cout ltlt Last ltlt ", " ltlt First
  • cout ltltendl

Program Output Enter your first and last names
and I will reverse them. Johnny Jones
Enter Jones, Johnny
12
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 arrays 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.

13
Check point 3.1
  • 3.1 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 gtgt value
  • 3.14
  • 3
  • 0
  • Nothing, an error message is displayed

ltiostreamgt
char
char customer53
14
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 ltlt (Operand1 operator Operand2)

Concept - C allows you to construct complex
mathematical expressions using multiple operators
and grouping symbols
15
Program 3-7 or 3-6 version 4
Mathematical expressions can be used in cout
statements. Note the inputs are integers but
they are converted to floats for storage
  • / This program asks the user top enter the
    numerator and denominator of a fraction and it
    displays the decimal value/
  • using namespace std
  • void main()?
  • float Numerator, Denominator
  •  
  • cout ltlt "This program shows the "
  • cout ltlt "decimal value of a fraction.\n"
  • cout ltlt "Enter the numerator "
  • cin gtgt Numerator
  • cout ltlt "Enter the denominator "
  • cin gtgt Denominator
  • cout ltlt "The decimal value is "
  • cout ltlt (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 0.1875
16
Precedence
  • If two operators share an operand the one with
    the highest precedence works first
  • highest - (Unary negation)?
  • /
  • Lowest -
  • Example 6 7 - 3 39 (not 24)?
  • Example 3 12 / 3 7 (not 5 )?

Mathematical expressions are evaluated left to
right
17
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
18
Grouping With Parentheses
  • Parentheses are used to force some operations to
    be performed before others
  • examples
  • (52)4 28
  • 10 / (5-3) 5
  • (4 17 ) 2 -1 0

19
No Exponents Please
  • Include the following file in your program to
    deal with exponents
  • include ltmathgt
  • 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 ?(radius2)?
  • 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
20
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 3.14159 /
  • include ltiostreamgt
  • include ltmath.hgt
  • using namespace stdvoid main()?
  • double Area, Radius
  • cout ltlt "This program calculates the "
  • cout ltlt " area of a circle.\n"
  • cout ltlt "What is the radius of "
  • cout ltlt "the circle? "
  • cin gtgt Radius
  • Area 3.14159 pow(Radius,2)
  • cout ltlt "The area is " ltlt Area

This program uses the pow function to find the
area of a circle
Program Output This program calculates the area
of a circle. What is the radius of the circle?
10 Enter The area is 314.159
21
Check Point 3.2
3.11 Write C expressions for the following
algebraic expressions y 6x a 2b 4c y
x2 x 2 g --------- z2
  • 3.10 Complete the table below by writing the
    value of each expression in the "Value" column.
  • Expression Value
  • 6 3 5
  • 12 / 2 4
  • 9 14 2 6
  • 5 19 3 1
  • (6 2 ) 3

y 6 x
21
2
a (2 b ) (4 c )
31
5
y pow( x,2)
24
g (x 2) / pow( z,2)
22
3.3 When you Mix Apples and Oranges Type
Coercion Rules
  • 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

Concept - When an operator's operands are of
different data types, C will automatically
convert them to the same data type
23
3.4 Overflow and Underflow
  • When a variable is assigned a value that is too
    large or too small in range for that variables
    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

24
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
25
Program 3-9 or 3-8 version 4
This program assumes that an integer is stored in
two bytes of memory
  • //This program demonstrates integer overflow and
    underflow
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • short TestVar 32767
  • cout ltlt TestVar ltlt endl
  • TestVar TestVar 1
  • cout ltlt TestVar ltlt endl
  • TestVar TestVar - 1
  • cout ltlt TestVar ltlt endl
  • Program Output
  • 32767
  • -32768
  • 32767

26
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 ltiostreamgt
  • using namespace std
  • void main()?
  • float Test
  • Test 2.0e38 1000
  • // Should overflow Test
  • cout ltlt Test ltlt endl
  • Test 2.0e-38 / 2.0e38
  • // Should underflow Test
  • cout ltlt Test ltlt endl

This compiler does not generate a runtime error
but the value stored may not be usable
Program Output 1.INF 0
27
3.5 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

28
Program 3-11 or 3-10 version 4
This program uses the type cast operator to avoid
integer division
  • include ltiostreamgt
  • using namespace std
  • void main()?
  • int Months, Books
  • float PerMonth
  • cout ltlt "How many books do you "
  • cout ltlt "plan to read? "
  • cin gtgt Books
  • cout ltlt "How many months will "
  • cout ltlt "it take you to read them? "
  • cin gtgt Months
  • PerMonth float(Books) / Months
  • cout ltlt "That is " ltlt PerMonth
  • cout ltlt " 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 4.285714
  • books per month.

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

30
Program 3-12 or 3-11 version 4
  • / This program uses a typecast operator to print
    a character from a number./
  •  
  • include ltiostreamgt
  •  
  • using namespace std
  • void main()?
  • int Number 65
  •  
  • cout ltlt Number ltlt endl
  • cout ltlt char(Number) ltlt endl

Program Output 65 A
31
The Power of Constants
  • Makes the program more readable
  • Simplifies maintenance
  • Example
  • const float PI 3.14159
  • or
  • define PI 3.14159
  • 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
32
Program 3-13 or 3-12 version 4
  • include ltiostreamgt
  • include ltmath.hgt
  • using namespace std
  • void main()?
  • const float Pi 3.14159
  • double Area, Radius
  • cout ltlt "This program calculates" cout ltlt " the
    area of a circle.\n"
  • cout ltlt "What is the radius of "
  • cout ltlt " the circle? "
  • cin gtgt Radius
  • Area Pi pow(Radius,2)
  • cout ltlt "The area is " ltlt Area

The literal 3.14159 has been replaced with a
floating point constant.
Program Output This program calculates the area
of a circle. What is the radius of the circle?
5 Enter The area is 78.5397
33
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 3.14159
  • is roughly the same as
  • const float PI3.14159

34
Program 3-14 or 3-13 version 4
  • include ltiostreamgt
  • include ltmathgt
  • // needed for pow function
  • define PI 3.14159
  • using namespace std
  • void main()?
  • double Area, Radius
  • cout ltlt "This program calculates"
  • cout ltlt " the area of a circle.\n"
  • cout ltlt "What is the radius of the"
  • cout ltlt " circle? "
  • cin gtgt Radius
  • Area PI pow(Radius, 2)
  • cout ltlt "The area is " ltlt Area
  •  

Remember that the preprocessor performs a textual
substitution. So each instance of Pi becomes a
floating point literal.
Program Output This program calculates the area
of a circle. What is the radius of the circle?
5 Enter The area is 78.5397
35
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.
36
Combined Assignment Operators
  • Eliminates the need to enter the variable name
    twice
  • Operator Example usage Equivalent 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
37
3.8 Formatting Output WithString 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
  • dec
  • hex
  • oct
  • scientific
  • showpoint
  • showpos
  • uppercase

Concept - The cout object provides ways to format
data as it is being displayed.
38
Program 3-17 or 3-15 version 4
  • //This program displays three rows of numbers
  • includeltiostream.hgt 
  • using namespace std
  • void main()?
  • 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 ltlt Num1 ltlt " "
  • cout ltlt Num2 ltlt " "
  • cout ltlt Num3 ltlt endl
  • // Display the second row of numbers
  • cout ltlt Num4 ltlt " "
  • cout ltlt Num5 ltlt " "
  • cout ltlt Num6 ltlt endl
  • // Display the third row of numbers
  • cout ltlt Num7 ltlt " "
  • cout ltlt Num8 ltlt " "

This program displays values with no output
formatting. There is no column alignment.
  • Program Output
  • 2897 5 837
  • 34 7 1623
  • 390 3456 12

39
Program 3-18 or 3-16 version 4
The setw command is used to line up the columns.
The default is right justified
  • /This program displays three rows of numbers. /
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • 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 ltlt setw(4) ltlt Num1 ltlt " "
  • cout ltlt setw(4) ltlt Num2 ltlt " "
  • cout ltlt setw(4) ltlt Num3 ltlt endl

// Display the second row of numbers cout ltlt
setw(4) ltlt Num4 ltlt " " cout ltlt setw(4) ltlt Num5
ltlt " " cout ltlt setw(4) ltlt Num6 ltlt endl //
Display the third row of numbers cout ltlt setw(4)
ltlt Num7 ltlt " " cout ltlt setw(4) ltlt Num8 ltlt "
" cout ltlt setw(4) ltlt Num9 ltlt endl
  • Program Output
  • 2897 5 837
  • 34 7 1623
  • 390 3456 12

40
Program 3-19 or 3-17 version 4
  • / This program demonstrates the setw manipulator
    being used with values of various data types. /
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • int IntValue 3928
  • float FloatValue 91.5
  • char StringValue14 "John J. Smith"
  • cout ltlt "(" ltlt setw(5)
  • cout ltlt IntValue ltlt ")" ltlt endl
  • cout ltlt "(" ltlt setw(8)
  • cout ltlt FloatValue ltlt ")" ltlt endl
  • cout ltlt "(" ltlt setw(16)
  • cout ltlt StringValue ltlt ")" ltlt endl

setw can format the output of any data type
  • Program Output
  • ( 3928)?
  • ( 91.5)?
  • ( John J. Smith)?

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

42
Program 3-20 or 3-18 version 4
  • / This program demonstrates how setprecision
    rounds floating point value. / 
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • float Quotient, Number1 132.364,
  • Number2 26.91Quotient Number1 /
    Number2cout ltlt Quotient ltlt endlcout ltlt
    setprecision(5) ltlt Quotient ltlt endlcout ltlt
    setprecision(4) ltlt Quotient ltlt endlcout ltlt
    setprecision(3) ltlt Quotient ltlt endlcout ltlt
    setprecision(2) ltlt Quotient ltlt endlcout ltlt
    setprecision(1) ltlt Quotient ltlt endl

setprecision does not truncate numbers it rounds
them up
  • Program Output
  • 4.91877
  • 4.9188
  • 4.919
  • 4.92
  • 4.9
  • 5

43
Table 3-11
  • Number Manipulator Value Displayed
  • 28.92786 setprecision(3) 28.9
  • 21. setprecision(5) 21
  • 109.5 setprecision(4) 109.5
  • 34.28596 setprecision(2) 34
  • cout ltlt fixed
  • 28.92786 setprecision(3) 28.928
  • 21. setprecision(5) 21.00000
  • 109.5 setprecision(4) 109.5000
  • 34.28596 setprecision(2) 34.29

44
Program for Table 3.11
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • cout ltlt " Number\t\tManipulator\t\tValue
    Displayed\n"
  • cout ltlt"28.92786\t setprecision(3)\t"ltlt
    setprecision(3) ltlt 28.92786 ltlt endl
  • cout ltlt"21.\t\t setprecision(5)\t"ltlt
    setprecision(5) ltlt 21. ltlt endl
  • cout ltlt"109.5\t\t setprecision(4)\t"ltlt
    setprecision(4) ltlt 109.5 ltlt endl
  • cout ltlt"34.28596\t setprecision(2)\t"ltlt
    setprecision(2) ltlt 34.28596 ltlt endl
  • cout ltlt"34.28596\t setprecision(1)\t"ltlt
    setprecision(1) ltlt 34.28596 ltlt endl
  • cout ltlt fixed
  • cout ltlt fixed\n"
  • cout ltlt"28.92786\t setprecision(3)\t"ltlt
    setprecision(3) ltlt 28.92786 ltlt endl
  • cout ltlt"21.\t\t setprecision(5)\t"ltlt
    setprecision(5) ltlt 21. ltlt endl
  • cout ltlt"109.5\t\t setprecision(4)\t"ltlt
    setprecision(4) ltlt 109.5 ltlt endl
  • cout ltlt"34.28596\t setprecision(2)\t"ltlt
    setprecision(2) ltlt 34.28596 ltlt endl

45
Program 3-21 or 3-19 version 4
This program will display 5 significant digits.
But what if the total takes 6
  • / This program asks for sales figures for 3
    days. The total sales is calculated and displayed
    in a table/
  • include ltiostreamgt
  • include ltiomanipgt
  •  
  • using namespace std
  • void main()?
  • float Day1, Day2, Day3, Total
  •  
  • cout ltlt "Enter the sales for day 1 "
  • cin gtgt Day1
  • cout ltlt "Enter the sales for day 2 "
  • cin gtgt Day2
  • cout ltlt "Enter the sales for day 3 "
  • cin gtgt Day3
  • Total Day1 Day2 Day3

cout ltlt "\nSales Figures\n" cout ltlt
"-------------\n" cout ltlt setprecision(5) cout
ltlt "Day 1 " ltlt setw(8) ltlt Day1 cout ltlt
endl cout ltlt "Day 2 " ltlt setw(8) ltlt Day2
cout ltlt endl cout ltlt "Day 3 " ltlt setw(8) ltlt
Day3 cout ltlt endl cout ltlt "Total " ltlt
setw(8) ltlt Total cout ltlt endl
46
Program Output
  • Enter the sales for day 1 321.57 Enter
  • Enter the sales for day 2 269.62 Enter
  • Enter the sales for day 3 1307.77 Enter
  •  
  • Sales Figures
  • -------------
  • Day 1 321.57
  • Day 2 269.62
  • Day 3 1307.8
  • Total 1899 The value has been truncated

47
Program 3-22 or 3-20 version 4
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • float Day1, Day2, Day3, Total
  • cout ltlt "Enter the sales for day 1 "
  • cin gtgt Day1
  • cout ltlt "Enter the sales for day 2 "
  • cin gtgt Day2
  • cout ltlt "Enter the sales for day 3 "
  • cin gtgt Day3
  • Total Day1 Day2 Day3
  • cout ltlt "\nSales Figures\n"
  • cout ltlt "------\n"
  • cout ltlt setprecision(2) ltlt setiosflags(iosfixed
    )
  • cout ltlt "Day 1 " ltlt setw(8) ltlt Day1 ltlt endl
  • cout ltlt "Day 2 " ltlt setw(8) ltlt Day2 ltlt endl
  • cout ltlt "Day 3 " ltlt setw(8) ltlt Day3 ltlt endl
  • Program Output (modified)
  • Enter the sales for day 1 321.00 Enter
  • Enter the sales for day 2 869.26 Enter
  • Enter the sales for day 3 403.77 Enter
  • Sales Figures
  • -------------
  • Day 1 321
  • Day 2 869.26
  • Day 3 403.77
  • Total 1594.90

The decimal point is displayed only if there are
digits to the right of it.
48
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.

49
Program 3-28 or 3-22 version 4
cin.getline will read one less character than the
second parameter specifies to make room for the
NULL character
  • // This program demonstrates cin's
  • // getline member function.
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • char String81
  • cout ltlt "Enter a sentence "
  • cin.getline(String, 81)
  • cout ltlt "You entered "
  • cout ltlt String ltlt endl

Program Output Enter a sentence To be, or not
to be. Enter You entered To be, or not to be.
50
Program 3-29 or 3-23 version 4
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • char Ch
  • cout ltlt "Type a character
  • cout ltlt " and press
  • cout ltlt " Enter "
  • cin gtgt Ch
  • cout ltlt "You entered " ltlt Ch ltlt endl

cin requires that the user enter only a single.
non white space character. All other input is
ignored.
Program Output Type a character and press
Enter A Enter You entered A
51
Program 3-30 or 3-23 version 4
  • include ltiostreamgt
  • include ltiomanipgt
  •  using namespace std
  • void main()?
  • char Ch
  •  
  • cout ltlt "This program has" cout ltlt " paused.
    Press"
  • cout ltlt " enter to continue."
  • cin.get(Ch)
  • cout ltlt "Thank you!"
  • cout ltlt endl

cin.get will accept any key, particularly the
return key
  • Program Output
  • This program has
  • paused. Press
  • Enter to continue.
  • Enter
  • Thank you!

52
Program 3-31 or 3-23? version 4
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • void main()?
  • char Ch
  •  
  • cout ltlt "Type a character" cout ltlt " and press
    Enter "
  • cin.get(Ch)
  • cout ltlt "You entered "
  • cout ltlt Ch ltlt endl
  • cout ltlt "Its ASCII code is "
  • cout ltlt int(Ch) ltlt endl
  •  

cin.get will accept non printable and white space
characters
  • Program Output
  • Type a character and press Enter Enter
  • You entered
  • Its ASCII code is
  • 10

53
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

54
More Mathematical Library Functions
  • abs
  • Absolute Value
  • exp
  • ex
  • fmod
  • modulus for floating point
  • cos
  • cosine
  • sin
  • sine
  • tan
  • tangent
  • log
  • natural log
  • log10
  • base 10 log
  • sqrt
  • square root

Concept - The C runtime library provides
several functions for performing complex
mathematical operations.
55
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.

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

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

58
Program 3-32 or 3-24 version 4
This program uses the sqrt function to find the
hypotenuse of a right triangle
  • include ltiostreamgt
  • include ltmathgt // For sqrt
  • using namespace std
  • void main()?
  • float A, B, C
  •  
  • cout ltlt "Enter the length of side A "
  • cin gtgt A
  • cout ltlt "Enter the length of side B "
  • cin gtgt B
  • C sqrt(pow(A, 2.0) pow(B, 2.0))
  • cout.precision(2)
  • cout ltlt "The length of the "
  • cout ltlt "hypotenuse is "ltlt C ltlt 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

59
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
60
Program 3-33 or 3-25 version 4
It still gives the same numbers for the same seed
value
  • // This program demonstrates random
  • //numbers.
  •  include ltiostreamgt
  • include ltstdlibgt
  •  
  • using namespace std
  • void main()?
  • unsigned Seed
  •  
  • cout ltlt "Enter a seed value "
  • cin gtgt Seed
  • srand(Seed)
  • cout ltlt rand() ltlt endl
  • cout ltlt rand() ltlt endl
  • cout ltlt rand() ltlt endl

Program Output Enter a seed value
5 1731 32036 21622 Program Output with Other
Example Input Enter a seed value
16 5540 29663 9920
61
Basic File I/O
  • The file fstream contains all the declarations
    necessary for file operations
  • include ltfstreamgt
  • 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

62
Reading from a file
  • Once the file has been opened you can read data
    from it similar to the way cin is used
  • InputFile gtgt 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.
Write a Comment
User Comments (0)
About PowerShow.com