Fundamentals of Programming
Elementary Programming
Data Types
Data Type Memory Range
int (integer numbers) 4 Bytes -2147483648 to
2147284647
short (integer numbers) 2 Bytes -32768 to 32767
char ( Character ) 1 Byte -128 to 127
float (real numbers) 4 Bytes 3.4x10-38 to 3.4x1038
double (real numbers) 8 Bytes 1.7 x10-308 to 1.7x10308
unsigned short (+ve numbers) 2 Bytes 0 to 65535
unsigned int (+ve numbers) 4 Bytes 0 to 4294967295
Fundamentals of Programming – 3 2
Writing a Simple Program
• Involves designing strategy/ algorithms and translating them
into programming instructions, or code
• Algorithm: describes how a problem is solved by listing the
actions that must be taken and the order of their execution
• Problem:Write a simple program to compute area of a circle
Fundamentals of Programming – 3 3
Writing a Simple Program
• The above breakdown of the problem can be translated to a
program as
Fundamentals of Programming – 3 4
Writing a Simple Program
• The program needs to read the radius entered by the user
from the keyboard. This raises two important issues:
1) Reading the radius 2) Storing the radius in the program
• In order to store radius and area, the program needs a
variable. A variable represents a value stored in the
computer’s memory.
‒ double is a data type: we declared two variables radius and area
Fundamentals of Programming – 3 5
Writing a Simple Program
• Rather than using x and y as variable names, choose
descriptive names: in this case, radius for radius, and area
for area. To let the compiler know what radius and area are,
specify their data types. That is the kind of the data stored
in a variable, whether integer, floating-point number, or
something else. This is known as declaring variables. C++
provides simple data types for representing integers,
floating-point numbers (i.e., numbers with a decimal point),
characters, and Boolean types. These types are known as
primitive data types or fundamental types.
• Next step is to prompt the user for entering value of radius
‒ Use cout to show the message
‒ Use cin to read entered value from the keyboard
Fundamentals of Programming – 3 6
Reading Input from the Keyboard
• Input from the keyboard is read by cin and stored in variable
Fundamentals of Programming – 3 7
Reading Input from the Keyboard
• cin (pronounced see-in) stands for console input. The >>
symbol, referred to as the stream extraction operator,
assigns an input to a variable. As shown in the sample run,
the program displays the prompting message "Enter a
radius: "; the user then enters number 2, which is assigned
to variable radius. The cin object causes a program to wait
until data is entered at the keyboard and the Enter key is
pressed. C++ automatically converts the data read from the
keyboard to the data type of the variable.
Fundamentals of Programming – 3 8
Reading Input from the Keyboard
• The >> operator is the opposite of the << operator. The >>
indicates that the data flows from cin to a variable. The <<
shows that the data flows from a variable or a string to cout.
You can think of the stream extraction operator >> as an
arrow that points to the variable and the stream insertion
operator << as an arrow that points to the cout, as shown
here:
Fundamentals of Programming – 3 9
Reading Input from the Keyboard
single cin statement can
read multiple inputs
You may enter three numbers separated by spaces, then press the Enter key,
or enter each number followed by the Enter key
Fundamentals of Programming – 3 10
Reading Input from the Keyboard
• Most of the programs in the early weeks of the course
perform three steps: input, process, and output, called IPO.
Input is receiving input from the user; process is producing
results using the input; and output is displaying the results.
Fundamentals of Programming – 3 11
Identifiers
• Identifiers are the names that identify elements such as
variables and functions in a program
• An identifier is a sequence of characters comprising letters,
digits, and underscores (_).
• An identifier must start with a letter or an underscore; it
cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix A,
“C++ Keywords,” for a list of reserved words.)
• An identifier can be of any length, but your C++ compiler
may impose restriction.
• Use identifiers of 31 characters or fewer to ensure
portability
Fundamentals of Programming – 3 12
Identifiers
• C++ Keywords
Fundamentals of Programming – 3 13
Identifiers
• Since C++ is case-sensitive, area, Area, and AREA are all
different identifiers.
• Identifiers are used to name variables, functions, and other
things in a program. Descriptive identifiers make programs
easy to read. Avoid using abbreviations for identifiers using
complete words is more descriptive. For example,
numberOfStudents is better than numStuds, numOfStuds,
or numOfStudents.
• Valid Identifiers???
Fundamentals of Programming – 3 14
Variables
• Variables are used to represent values that may be changed
in the program
Fundamentals of Programming – 3 15
Variables
• Variables are used to represent data of a certain type.
• To use a variable, you declare it by telling the compiler its
name as well as the type of data it can store.
• The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on its
data type.
• The syntax for declaring a variable is
Fundamentals of Programming – 3 16
Variables
• If variables are of the same type, they can be declared
together, as follows:
• We say “declare a variable,” but not “define a variable.” We
are making a subtle distinction here. A definition defines
what the defined item is, but a declaration usually
involves allocating memory to store data for the declared
item.
Fundamentals of Programming – 3 17
Variables
• Variables often have initial values. You can declare a variable
and initialize it in one step.
Both are Equivalent
• A variable must be declared before it can be assigned a
value. A variable declared in a function must be assigned a
value. Otherwise, the variable is called uninitialized and its
value is unpredictable often called garbage value. Whenever
possible, declare a variable and assign its initial value in one
step. This will make the program easy to read and will avoid
programming errors.
• Variable must be declared & initialized before it can be
used.
Fundamentals of Programming – 3 18
Variables
• Identify and fix the errors in the following code
Fundamentals of Programming – 3 19
Assignment Statements and Assignment Expressions
• An assignment statement designates a value for a variable.
An assignment statement can be used as an expression
• An expression represents a computation involving values,
variables, and operators that, taking them together,
evaluates to a value
Fundamentals of Programming – 3 20
Assignment Statements and Assignment Expressions
• In mathematics, x = 2 * x + 1 denotes an equation. However,
in C++, x = 2 * x + 1 is an assignment statement that
evaluates the expression 2 * x + 1 and assigns the result to
the variable x.
• In C++, an assignment statement is essentially an expression
that evaluates to the value to be assigned to the variable on
the left side of the assignment operator. For this reason, an
assignment statement is also known as an assignment
expression.
Fundamentals of Programming – 3 21
Assignment Statements and Assignment Expressions
• Identify and fix the errors in the following code
Fundamentals of Programming – 3 22
Named Constants
• A named constant is an identifier that represents a
permanent value.
• The value of a variable may change during the execution of
a program, but a named constant, or simply constant,
represents permanent data that never changes.
• In example of circle area, value of Pi is a constant. If you use
it frequently, you don’t want to keep typing 3.14159;
instead, you can declare a constant for Pi
Fundamentals of Programming – 3 23
Named Constants
Fundamentals of Programming – 3 24
Named Constants
• By convention, constants are named in uppercase: PI, not pi,
Pi or _Pi
• There are three benefits of using constants:
‒ you don’t have to repeatedly type the same value;
‒ if you have to change the constant value (e.g., from 3.14 to 3.14159
for PI), you need change it only in a single location in the source
code;
‒ descriptive constant names make the program easy to read.
Fundamentals of Programming – 3 25
Numeric Data Types and Operations
• C++ has nine numeric types for integers and floating-point
numbers with operators +, -, *, /, and %
• Every data type has a range of values. The compiler
allocates memory space for each variable or constant
according to its data type. C++ provides primitive data types
for numeric values, characters, and Boolean values
Fundamentals of Programming – 3 26
Numeric Data Types and Operations
Fundamentals of Programming – 3 27
Numeric Data Types and Operations
• C++ uses three types for integers: short, int, and long. Each
integer type comes in two flavors: signed and unsigned. Half
of the numbers represented by a signed int are negative
and the other half are non-negative. All the numbers
represented by an unsigned int are nonnegative. Because
you have the same storage size for both, the largest number
you can store in an unsigned int is twice as big as the largest
positive number you can store in a signed int. If you know
the value stored in a variable is always nonnegative, declare
it as unsigned.
• short int is synonymous with short. unsigned short int is
synonymous with unsigned short. unsigned is synonymous
with unsigned int. long int is synonymous with long.
unsigned long int is synonymous with unsigned long
Fundamentals of Programming – 3 28
Numeric Data Types and Operations
• C++ uses three types for floating-point numbers: float,
double, and long double. The double type is usually twice
as big as float. So, the double is known as double precision,
while float is single precision. The long double is even
bigger than double. For most applications, using the double
type is desirable.
• For convenience, C++ defines constants INT_MIN,
INT_MAX, LONG_MIN, LONG_MAX, FLT_MIN, FLT_MAX,
DBL_MIN, and DBL_MAX in the <limits> header file
Fundamentals of Programming – 3 29
Numeric Data Types and Operations
• The size of the data types may vary depending on the
compiler and computer you are using. Typically, int and long
have the same size. On some systems, long requires 8 bytes.
You can use the sizeof function to find the size of a type or a
variable on your machine.
Fundamentals of Programming – 3 30
Numeric Data Types and Operations
• Numeric Literals
‒ A literal is a constant value that appears directly in a program. In
the following statements, for example, 34 and 0.305 are literals
• By default, an integer literal is a decimal integer number. To
denote an octal integer literal, use a leading 0 (zero), and to
denote a hexadecimal integer literal, use a leading 0x or 0X
(zero x). For example, the following code displays the
decimal value 65535 for hexadecimal number FFFF and
decimal value 8 for octal number 10.
Fundamentals of Programming – 3 31
Numeric Data Types and Operations
• Floating-point literals can be written in scientific notation in
the form of a * 10b. For example, the scientific notation for
123.456 is 1.23456 * 102 and for 0.0123456 it’s 1.23456 * 10-
2
. A special syntax is used to write scientific notation
numbers. For example, 1.23456 * 102 is written as 1.23456E2
or 1.23456E+2 and 1.23456 * 10-2 as 1.23456E-2. E (or e)
represents an exponent and can be in either lowercase or
uppercase.
• The float and double types are used to represent numbers
with a decimal point. Why are they called floating-point
numbers? These numbers are stored in scientific notation
internally. When a number such as 50.534 is converted into
scientific notation, such as 5.0534E+1, its decimal point is
moved (i.e., floated) to a new position.
Fundamentals of Programming – 3 32
Numeric Data Types and Operations
• Numeric Operators
‒ The operators for numeric data types include the standard
arithmetic operators: addition (+), subtraction (–), multiplication
(*), division (/), and remainder (%)
‒ The operands are the values operated by an operator
Fundamentals of Programming – 3 33
Numeric Data Types and Operations
• When both operands of a division are integers, the result of
the division is the quotient and the fractional part is
truncated. For example, 5 / 2 yields 2, not 2.5, and –5 / 2
yields -2, not –2.5. To perform regular mathematical
division, one of the operands must be a floating point
number. For example, 5.0 / 2 yields 2.5
• The % operator, known as modulo or remainder operator,
works only with integer operands and yields the remainder
after division.
Fundamentals of Programming – 3 34
Numeric Data Types and Operations
• Suppose you and your friends are going to meet in 10 days.
What day is in 10 days? You can find that day is Tuesday
using the following expression:
Fundamentals of Programming – 3 35
Numeric Data Types and Operations
• Following program obtains minutes and remaining seconds
from an amount of time in seconds. For example, 500
seconds contains 8 minutes and 20 seconds .
Fundamentals of Programming – 3 36
Numeric Data Types and Operations
• The pow(a, b) function can be used to compute ab. pow is a
function defined in the cmath library. The function is
invoked using the syntax pow(a, b) (i.e., pow(2.0, 3)) that
returns the result of ab (23). Here, a and b are parameters
for the pow function and numbers 2.0 and 3 are actual
values used to invoke the function.
• Google cmath to find other math functions
Fundamentals of Programming – 3 37
Evaluating Expressions and Operator Precedence
• C++ expressions are evaluated in the same way as
arithmetic expressions
Fundamentals of Programming – 3 38
Evaluating Expressions and Operator Precedence
• Operators contained within pairs of parentheses are
evaluated first. Parentheses can be nested, in which case
the expression in the inner parentheses is evaluated first.
When more than one operator is used in an expression the
following operator precedence rule is used to determine
the order of evaluation.
‒ Multiplication, division, and remainder operators are applied next.
If an expression contains several multiplication, division, and
remainder operators, they are applied from left to right.
‒ Addition and subtraction operators are applied last. If an expression
contains several addition and subtraction operators, they are
applied from left to right.
Fundamentals of Programming – 3 39
Evaluating Expressions and Operator Precedence
Fundamentals of Programming – 3 40
Augmented Assignment Operators
• The operators +, -, *, /, and % can be combined with the
assignment operator to form augmented operators.
• Often, the current value of a variable is used, modified, and
then reassigned back to the same variable. For example, the
following statement increases the variable count by 1:
• C++ allows you to combine assignment and addition
operators using an augmented assignment operator. For
example, the preceding statement can be written as follows:
Fundamentals of Programming – 3 41
Augmented Assignment Operators
• The augmented assignment operator is performed last after
the other operators in the expression are evaluated
Fundamentals of Programming – 3 42
Increment and Decrement Operators
• The increment (++) and decrement (--) operators are for
incrementing and decrementing a variable by 1
Fundamentals of Programming – 3 43
Increment and Decrement Operators
• postfix i++ and prefix ++I
After following code, x becomes 0.1, y becomes 6.4, and z
becomes 7.5
Fundamentals of Programming – 3 44
Increment and Decrement Operators
Fundamentals of Programming – 3 45
Numeric Type Conversions
• If an integer and a floating-point number are involved in a
binary operation, C++ automatically converts the integer to
a floating-point value. So, 3 * 4.5 is the same as 3.0 * 4.5. C+
+ also allows you to convert a value from one type to
another explicitly by using a casting operator. The syntax is
static_cast<type>(value), where the value is a variable,
numeric literal or expression. For example, the following
statement sets variable i to 5.
Fundamentals of Programming – 3 46
Numeric Type Conversions
• Casting a variable of a type with a small range to a variable
of a type with a larger range is known as widening a type.
Casting a variable of a type with a large range to a variable
of a type with a smaller range is known as narrowing a type.
Narrowing a type, such as assigning a double value to an int
variable, may cause loss of precision. Lost information might
lead to inaccurate results. The compiler gives a warning
when you narrow a type, unless you use static_cast to make
the conversion explicit.
Fundamentals of Programming – 3 47
Common Errors
• Undeclared/Uninitialized Variables and Unused Variables
• Integer Overflow
• Round-off Errors
• Unintended Integer Division
• Forgetting Header Files
Fundamentals of Programming – 3 48
2.10 Case Study: Displaying the Current Time
• You can invoke the time(0) function to return the current
time.
• The time(0) function, in the ctime header file, returns the
current time in seconds elapsed since the time 00:00:00 on
January 1, 1970 GMT.
Fundamentals of Programming – 3 49
2.15 Case Study: Counting Monetary Units
• The program lets the user enter an amount as a double
value representing a total in dollars and cents, and outputs a
report listing the monetary equivalent in the maximum
number of dollars, quarters, dimes, nickels, and pennies
Fundamentals of Programming – 3 50
Thanks
Fundamentals of Programming – 3 5