COMP 152 – PROGRAMMING I PROBLEM SOLVING USING C++
Instructor: Dr Dionysiou
ADMINISTRATIVE
! This week’s lecture [BRON06] Chapter 1 (1.4)
! Flowcharts
[BRON06] Chapter 2 (2.1-2.5) ! Introduction to C++, data types, arithmetic operations,
variables and declarations statements
! Visual Studio .Net (C++) 2008, express edition Available for free from www.microsoft.com/express
Copyrigh
t © D
ionysiou
2010
LECTURE OUTLINE
! Flowcharts ! Introduction to C++ ! Data Types ! Arithmetic Operations ! Variables and Declaration Statements
Copyrigh
t © D
ionysiou
2010
FLOWCHARTS
! Write an algorithm that solves the following problem
Calculate the average of 3 numbers
Copyrigh
t © D
ionysiou
2010
FLOWCHARTS (CONT.)
! Solution 1 (using pseudocode) 1. Input three values 1.1 Input value A
1.2 Input value B 1.3 Input value C
2. Calculate the average 2.1 Use formula (A+B+C)/3 3. Display the average
Copyrigh
t © D
ionysiou
2010
FLOWCHARTS (CONT.)
! Solution 2 (using flowchart) Start
End
Input 3
values
Display the
average
Calculate the
average
Copyrigh
t © D
ionysiou
2010
FLOWCHARTS (CONT.)
Indicates the beginning or end on an algorithm
Input or output
operation
Indicates computation or
data manipulation
Indicates a program branch point
loop Copyrigh
t © D
ionysiou
2010
FLOWCHARTS
! Write an algorithm that solves the following problem
Interchange the contents of two cups of liquid. Assume that a third cup is available to hold the contents of either cup temporarily. Each cup should be rinsed before any liquid is poured into it.
Copyrigh
t © D
ionysiou
2010
FLOWCHARTS (CONT.)
Start
End
Get cups A,
B, C
Display cups A,
B
Pour liquid from A to C
Rinse A
Pour liquid from B to A
Rinse B
Pour liquid from C to B
Copyrigh
t © D
ionysiou
2010
EXERCISES
! Write an algorithm that solves the following problems: Sort 2 numbers in increasing order Sort 3 numbers in increasing order Calculate your GPA for the previous semester Count how many positive and how many negative
numbers a user entered Count how many cents you have in your wallet\pocket
\purse Count how many times the word “program” occurs in a
document. Find the sum of the numbers 1+2+3+4+…+100
Copyrigh
t © D
ionysiou
2009
LECTURE OUTLINE
! Flowcharts ! Introduction to C++ ! Data Types ! Arithmetic Operations ! Variables and Declaration Statements
Copyrigh
t © D
ionysiou
2010
INTRODUCTION TO C++
! Modular programs Structure consists of interrelated segments, arranged in
logical order to form complete unit
! Modules Smaller segments used to construct modular program
! Designed to perform specific task ! Small subprograms – functions
Input Function Output
Copyrigh
t © D
ionysiou
2010
INTRODUCTION TO C++ (CONT.)
! Interface of the function Inputs Outputs
! Function operation Convert inputs to outputs (results) Encapsulated within the function
First Number
Second Number
sumTwoNums
A + B
Summation Result
Copyrigh
t © D
ionysiou
2010
HOW TO NAME OUR FUNCTIONS?
! Identifiers Names of functions, variables, etc. Naming Convention (rules to obey!)
! The first character of the name must be a letter or underscore ( _ ) ! number1
! Only letters, digits, or underscores may follow the initial letter; separate words in a name consisting of multiple words by capitalizing the first letter of one or more of the words ! sumOfNumbers
! An identifier cannot be a keyword ! Word with special purpose in the language
const, new, etc
! The maximum number of characters in an identifier is limited to 255
Copyrigh
t © D
ionysiou
2010
HOW TO NAME OUR FUNCTIONS?
! Identifier name must be mnemonic! ! How would you name a function that adds 2 numbers?
! function1 ! sum ! sumTwoNumbers ! sum2Numbers ! functionThatSumsTwoNumbers
! C++ is case-sensitive language!!! sumTwoNumbers SumTwoNumbers 3 distinct identifiers sUMtwoNUMbers
Copyrigh
t © D
ionysiou
2010
HOW TO NAME OUR FUNCTIONS (CONT.)
C++ Keywords Copyrigh
t © D
ionysiou
2010
THE main() FUNCTION
! C++ program must have exactly one function named main() Driver function
! Function header line First line of function consists of 3 pieces of information
! What type of data is returned from function ! Keyword before function name defines type of value function
returns ! Name of function ! What type of data is sent into function
! Arguments: Data transmitted to function at run time
! Function body Braces, { and }, denote beginning and end of function body
! Statements inside determine what function does ! Statements end with semicolon (;)
Copyrigh
t © D
ionysiou
2010
THE main() FUNCTION
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM
Hello COMP152 class!! :)
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
Comments Explanatory remarks within program Line comments Begin with two slashes (//) and continue to end of line Block comments Begin with /* and end with */ and can span multiple lines
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
Preprocessor command Perform some action before the compiler translates the source program into machine code #include preprocessor command causes the contents of a file to be inserted in that specific position
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
#include <iostream> iostream is part of the standard library that contains, among other code, two classes (istream and ostream) iostream is also called a header file cout is created from ostream
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
using namespace std; tells the compiler where to look to find the header files
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
using namespace std; Building name #include <iostream> Floor # cout Room #
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
int main( ) driver function takes no arguments returns an integer value consists of 2 statements Enclosed within { }
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
cout << “Hello COMP152 class!! :)”; cout is object of a prewritten class ostream when string of characters is passed to cout, the object displays it on the monitor (put to operator <<) Strings: Combination of letters, numbers, and special characters enclosed in double quotes
Copyrigh
t © D
ionysiou
2010
A SIMPLE PROGRAM (CONT.)
return 0; The main() function has a return value, which must be an integer value it returns 0 to the main program
Copyrigh
t © D
ionysiou
2010
ANOTHER SIMPLE PROGRAM
Hello COMP152 class!! :) My name is Ioanna
Copyrigh
t © D
ionysiou
2010
ANOTHER SIMPLE PROGRAM (CONT.)
Hello COMP152 class!! :)My name is Ioanna
Copyrigh
t © D
ionysiou
2010
ANOTHER SIMPLE PROGRAM (CONT.)
Hello COMP152 class!! :) My name is Ioanna
Copyrigh
t © D
ionysiou
2010
ANOTHER SIMPLE PROGRAM (CONT.)
Hello COMP152 class!! :) My name is Ioanna
\n Newline escape sequence Backslash (\) character provides “escape” from the normal interpretation of following character It tells cout to send instructions to the display device and to move to a new line
Copyrigh
t © D
ionysiou
2010
ESCAPE SEQUENCES
Copyrigh
t © D
ionysiou
2010
ESCAPE SEQUENCES (CONT.)
Copyrigh
t © D
ionysiou
2010
IN-CLASS EXERCISES
Replace the 2 cout statements by the following: cout << “Hello COMP152 class!!”; cout << “\n My name is Ioanna”; Replace the 2 cout statements by the following: cout << “Hello COMP152 class!!\n My name is Ioanna”; Replace the cout statement by the following: cout << “Hello COMP152 \n\n class!!\n My name is Ioanna”;
Copyrigh
t © D
ionysiou
2010
IN-CLASS EXERCISES (CONT.)
Write a C++ program that displays the following output:
SCORE GRADE
100 A
80 B
70 C
60 D
C
opyright ©
Dion
ysiou 2010
LECTURE OUTLINE
! Flowcharts ! Introduction to C++ ! Data Types ! Arithmetic Operations ! Variables and Declaration Statements
Copyrigh
t © D
ionysiou
2010
DATA TYPES
! Data is classified into specific types interest on loan (numerical type) student name (character-based type)
! Data type Set of values and operations applicable to these values
! Prevent programmer from attempting to perform illegal operations Suppose I have two numbers 2,3 and two strings
“school”, “work” ! Add the numbers ! Add the strings ! Concatenate the strings ! Concatenate the numbers
Copyrigh
t © D
ionysiou
2010
DATA TYPES (CONT.)
! Built-in data type: Provided as integral part of the C++ language No external C++ code required Also called Primitive types, because they can store only
one “thing”
! Literal: An acceptable value for data type Also called a constant Examples
! 7 ! 12.34 ! “hello world!” ! ‘a’
Copyrigh
t © D
ionysiou
2010
DATA TYPES (CONT.)
! The built-in data types can be divided into two categories Integer types
! stores whole numbers
Floating-point type ! stores decimal numbers
Copyrigh
t © D
ionysiou
2010
DATA TYPES (CONT.)
! The operations that can be performed on the built-in data types are also be divided into two categories
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES
considered an integer data type as
internally it is stored as a number
! Essential difference among the various types is the amount of storage used for each type
! That affects the range of values that each type is capable of representing
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – int DATA TYPE
! Set of values supported by the int data type Whole numbers (integers) Consists of digits Optionally may be preceded by either + or –
! Examples of valid integers 0 5 -2 +56
! What is the largest and smallest integer value that can be stored in the int data type? Depends on storage allocation for int by the compiler Usually 4 bytes (32 bits)
! �2,147,483,648 to +2,147,483,647
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – char DATA TYPE
! Used to store individual characters Letters of alphabet (upper and lower case) Digits 0 through 9 Special symbols such as + $ . , !
! Enclosed by single quotes
! Examples of valid characters ‘5’ ‘a’ ‘!’ ‘B’
! Typically stored using ASCII (American Standard Code for Information Interchange) or Unicode Each character is stored in 1 byte (ASCII) or 2 bytes (Unicode) 256 distinct codes (ASCII) or 65,536 (Unicode)
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – char DATA TYPE (CONT.)
! ASCII for uppercase letters ‘A’ has ASCII code 01000001 (integer value 65)
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – bool DATA TYPE
! Set of values supported by the bool data type True or false 0 or 1
! Boolean values are used in Boolean conditions This discussion will wait until selection control structure
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – signed and unsigned DATA TYPE ! Signed data type
Permits storage of negative values ! e.g., int
! Unsigned data type Only non-negative values
! e.g., char and bool
! Unsigned integer types have double the range of signed counterparts Why??
Copyrigh
t © D
ionysiou
2010
INTEGER DATA TYPES – signed and unsigned DATA TYPE
Copyrigh
t © D
ionysiou
2010
DETERMINING STORAGE SIZE
! In C++ the size of a data type is compiler dependent you cannot be sure what is the largest/smallest value
you can store in a data type ! However, there is a standard of a minimum expected size of the
built-in data types
! sizeof() operator Provides number of bytes used to store values for
various data types
Copyrigh
t © D
ionysiou
2010
DETERMINING STORAGE SIZE (CONT.)
Copyrigh
t © D
ionysiou
2010
FLOATING-POINT TYPES
! Floating-point number Number containing a decimal point
! Also called a real number ! 10.2 2.3 +1.0 -1.0 1. ! Note that 1.0 is classified as floating-point value whereas 1 is
classified as integer value
! Three floating-point data types float (single precision)
! Literal indicated by appending f or F after number double (double precision) long double
! Literal indicated by appending l or L after number
! In the absence of suffixes, a floating number defaults to a double 9.234 indicates a double literal 9.234f indicates a float literal 9.234L indicates a long double literal
Copyrigh
t © D
ionysiou
2010
FLOATING-POINT TYPES (CONT.)
! Difference among the 3 types is the amount of storage that the compiler is using to store them Most compilers use twice the amount of storage for doubles as for
floats Float – single-precision Double – double precision
ANSI C++ standard requires that Double has at least the same precision as a float Long double has at least the same storage as a double
Most C++ compilers Float 4 bytes Double and long double 8 bytes
Copyrigh
t © D
ionysiou
2010
FLOATING-POINT TYPES – EXPONENTIAL NOTATION
! Similar to scientific notation Used to express very large and very small values in
compact form Letter e stands for exponent
! Number following e represents power of 10 ! Indicates number of places the decimal point should be moved
to obtain the standard decimal value ! Move to the right (if number after e is positive) ! Move to the left (if number after e is negative)
Decimal Notation Exponential Notation Scientific Notation
1625. 1.625e3 1.625 x 103
63421. 6.3421e4 6.3421 x 104
.00731 7.31e-3 7.31 x 10-3
.000625 6.25e-4 6.25 x 10-4
Copyrigh
t © D
ionysiou
2010
IN-CLASS EXERCISE
Modify the program below to determine how many bytes your compiler assigns to all data types supported by C++
Copyrigh
t © D
ionysiou
2010
LECTURE OUTLINE
! Flowcharts ! Introduction to C++ ! Data Types ! Arithmetic Operations ! Variables and Declaration Statements
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS
! Integer and real numbers can be added, subtracted, multiplied, and divided. You can also add and subtract characters It’s possible because characters are stored using integer
codes ! ‘A’ + 1 will result in character ‘B’
Operation Operator
Addition + Subtraction - Multiplication * Division / Modulus Division %
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS (CONT.)
! These operators are called binary operators operand operator operand
! Examples of simple binary arithmetic expression 3 + 7 18 – 2 12.3 * 2.0 12.6 / 2.
Operation Operator
Addition + Subtraction - Multiplication * Division / Modulus Division %
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS (CONT.)
! You can use cout to display the value of any arithmetic expression on the console Pass the desired value to the cout object
cout << (6 + 15); cout << “ The sum of 6 and 15 is “ << (6 + 15);
cout << “ The sum of 6 and 15 is “ << (6 + 15);
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS (CONT.)
manipulator (more in [BRON06], chapter 3) an item used to manipulate how the output stream of characters is displayed endl manipulator causes a new line character ‘\n’ to be inserted into the display and then forces all of the current insertions to be displayed immediately
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – EXPRESSION TYPES
! Expression Combination of operators and operands evaluated to
yield value
! Expression Types Integer expression
! Operands and result are integer values
Floating-point expression ! Operands and result are floating-point values
Mixed-mode expressions ! Operands are mixture of integer and floating-point values
! If both operands are integer values, result is integer ! If one operand is floating-point value, result is double-
precision value
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – INTEGER DIVISION
! Division of two integer values always yield an integer value 10 / 2 yields 5 15 / 2 yields 7 9 / 4 yields 2 20 / 3 yields 6
! Only the integer part of the result is obtained!
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – INTEGER DIVISION (CONT.)
! Remainder of an integer division can be obtained with the modulus operation 10 % 2 yields 0 15 % 2 yields 1 9 % 4 yields 1 20 % 3 yields 2
! Only the fractional part of the division is obtained!
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – NEGATION
! Unary operation (-) Single operand Negates the number
! -(-5) is 5
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – SUMMARY
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – PRECEDENCE
! Rules when writing expressions containing more than one arithmetic operator: Cannot place two binary arithmetic operator symbols
side by side Parentheses may be used to form groupings Sets of parentheses may be enclosed by other
parentheses Parentheses not used to indicate multiplication
! E.g. (3 + 4)(5 + 1) is wrong have to be (3 + 4) * (5 + 1)
! C++ uses the same precedence rules as in general mathematics ! Rule 1: All negations are done first ! Rule 2: Second multiplication, division, and modulus
are evaluated from left to right ! Rule 3: Finally, addition and subtraction are
evaluated from left to right
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – PRECEDENCE (CONT.)
! Parentheses should specify logical groupings of operands
By using parentheses you can overwrite the default operator precedence
If you are not sure about the precedence, it doesn’t hurt to use parentheses
Using parentheses improves readability of the expression
Copyrigh
t © D
ionysiou
2010
ARITHMETIC OPERATIONS – ASSOCIATIVITY
! Operators have associativity Order in which operators of the same precedence are
evaluated as described earlier in Rule 2
Copyrigh
t © D
ionysiou
2010
IN-CLASS EXERCISE
Write a program to determine the value of the expressions in [BRON06] page 110, Exercise 2
Copyrigh
t © D
ionysiou
2010
LECTURE OUTLINE
! Flowcharts ! Introduction to C++ ! Data Types ! Arithmetic Operations ! Variables and Declaration Statements
Copyrigh
t © D
ionysiou
2010
VARIABLES
! All values used in computer program are stored in the computer’s memory unit
! Variables
Symbolic names used in place of memory addresses ! Value stored in variable can change
! Assignment statement Tells computer to assign value to variable
! Always have equal (=) sign and one variable name immediately to left of sign
Copyrigh
t © D
ionysiou
2010
VARIABLES (CONT.)
45
num1
1652 123
num2
2222 168
A
2260
Variable name
Variable address
Variable content
Copyrigh
t © D
ionysiou
2010
VARIABLES (CONT.)
45
num1
1652 123
num2
2222 168
A
2260
Variable name
Variable Naming Rules = Identifier Rules
Copyrigh
t © D
ionysiou
2010
VARIABLES (CONT.)
45
num1
1652 123
num2
2222 168
A
2260
Variable content
Variable Content – change via assignment statements
Copyrigh
t © D
ionysiou
2010
VARIABLES (CONT.)
45
num1
1652 123
num2
2222 168
A
2260
Variable address Assigned by the compiler
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT
num1
1652
num2
2222
A
2260
! Declaration statement Naming a variable and specifying the data type that can
be stored datatype variableName;
! Assignment statement Assigning a value into a variable
variableName = expression;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
num1
1652
num2
2222
A
2260
! Let’s declare an integer variable named num1 int num1;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
45
num1
1652
num2
2222
A
2260
! Let’s change the contents of variable num1 to store 45
num1 = 45;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
45
num1
1652
num2
2222
A
2260
! Let’s declare a float variable named num2 float num2;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
45
num1
1652 123.0
num2
2222
A
2260
! Let’s change the contents of variable num2 to store 123
num2 = 123;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
45
num1
1652 123.0
num2
2222 168.0
A
2260
! Let’s change the contents of variable A to contain the sum of the contents of num1 and num2
float A;
A = num1 + num2;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
! Multiple Declarations Variables having the same data type can always be
grouped together and declared using a single declaration statement
datatype variableName List;
double num1; double num1, num2; double num2;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
! Variable Initialization Use the declaration statement to declare and assign a
value for a variable datatype variableName = expression;
char letter1 = ‘a’;
Copyrigh
t © D
ionysiou
2010
VARIABLE DECLARATION AND ASSIGNMENT (CONT.)
! Tips on declaration and assignment Variable declarations may be intermixed within a
program ! Only requirement is that a variable must be declared prior to
its use
It is preferable to group declarations at the top of each functions ! Exceptions: e.g. declare a loop variable at its point of use
Copyrigh
t © D
ionysiou
2010
EXAMPLES
Copyrigh
t © D
ionysiou
2010
EXAMPLES (CONT.)
Copyrigh
t © D
ionysiou
2010
VARIABLE’S ADDRESS
! Every variable has three major items associated with it: Data type, value, and variable’s address
! Address is first memory location used for variable
! To determine address of variable, use C++’s address operator (&) “the address of” The address of a variable may be different every time
that the application runs
Copyrigh
t © D
ionysiou
2010
VARIABLE’S ADDRESS (CONT.)
Get the address of the variable
This is the address
Copyrigh
t © D
ionysiou
2010