PROGRAMMING 2.
LESSON 2
C++ Programming: From Problem Analysis to
LESSON 1
Program Design
TYPES OF PROGRAMMING LANGUAGE
Introduction
LOW LEVEL LANGUANGE • Computer program: sequence of statements
-Machine level language designed to accomplish some task
-Assemly level language • Programming: planning/creating a program
HIGH LEVEL LANGUANGE • Syntax: rules that specify which statements
-Procedural orientated language (instructions) are legal
-Problem oriented language • Programming language: a set of rules, symbols, and
-Natural language special words
• Semantic rule: meaning of the instruction
C++ VARIABLE C++ Programs
C++ Identifiers • A C++ program is a collection of one or more
-keywords/ reserved words vs. Identities subprograms, called functions
-Case-sensitivity and validity of identifiers • A subprogram or a function is a collection of
-Meaningful name statements that, when activated (executed),
Variable accomplishes something
-A memory location to store data for a program • Every C++ program has a function called main
-Must declare all data before use in program • The smallest individual unit of a program written in
any language is called a token
Symbols 1.1
PROGRAM, PROGRAMMING, AND PROGRAMMING
• Special symbols
LANGUAGE
+ ?
Program: the set of instructions which instruct the - ,
computer to perform certain particular operations is * <=
called a program / !=
Programming: It is the process of writing a program . ==
following the program of the programming language ; >=
Programming language: it is simply decoded
language used by programmers to write instruction Symbols 1.2
that a computer can understand to do what the • Word symbols
program want − Reserved words, or keywords
− Include:
• int
• float
• double
• char
• void
• return
Identifiers
• Consist of letters, digits, and the underscore
character (_)
• Must begin with a letter or underscore
• C++ is case sensitive
• Some predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may
be redefined, but it is not a good idea
Legal and Illegal Identifiers • Some of the values belonging to char data type
• The following are legal identifiers in C++: are: 'A', 'a', '0' , '*' , '+', '$', '&'
− first A blank space is a character and is written ' ', with a space left
− conversion between the single quotes
− payRate
Floating-Point Data Types
• C++ uses scientific notation to represent real numbers
(floating-point notation)
Data Types
• Data Type: set of values together with a set of operations is
called a data type
• C++ data can be classified into three categories: Floating-Point Data Types (continued)
− Simple data type • float: represents any real number − Range: -3.4E+38 to
− Structured data type 3.4E+38
− Pointers • Memory allocated for the float type is 4 bytes
• double: represents any real number − Range: -1.7E+308
Simple Data Types to 1.7E+308
• Three categories of simple data • Memory allocated for double type is 8 bytes
− Integral: integers (numbers without a decimal) • On most newer compilers, data types double and long
− Floating-point: decimal numbers double are same
− Enumeration type: user-defined data type
Arithmetic Operators
• C++ Operators
+ addition
- subtraction
* multiplication
/ division
int Data Type
% remainder (mod operator)
• Examples:
• +, -, *, and / can be used with integral and floating-point
-6728
data types
0
• Unary operator - has only one operand
78
• Binary Operator - has two operands
• Positive integers do not have to have a + sign in front of
them
Order of Precedence
• No commas are used within an integer
• All operations inside of () are evaluated first
• Commas are used for separating items in a list
• * , /, and % are at the same level of precedence and are
evaluated next
bool Data Type
• + and – have the same level of precedence and are
• bool type − Has two values, true and false − Manipulate
evaluated last
logical (Boolean) expressions
• When operators are on the same level
• true and false are called logical values
− Performed from left to right
• bool, true, and false are reserved words
char Data Type
• The smallest integral data type
• Used for characters: letters, digits, and special symbols
• Each character is enclosed in single quotes
Evaluate each of the following C++ expressions and write the string Data Type
final value in the space provided. Pay close attention to • Programmer-defined type supplied in standard library
operator precedence and data type conversions • Sequence of zero or more characters
• Enclosed in double quotation marks
• Null: a string with no characters
• Each character has relative position in string
• Position of first character is 0, the position of the second is
1, and so on
• Length: number of characters in string
Input
• Data must be loaded into main memory before it can be
Expressions
manipulated
• If all operands are integers
• Storing data in memory is a two-step process:
− Expression is called an integral expression
1. Instruct the computer to allocate memory
• If all operands are floating-point
2. Include statements to put data into allocated memory
− Expression is called a floating-point expression
• An integral expression yields integral result
Allocating Memory
• A floating-point expression yields a floating-point result
• Named Constant: memory location whose content can’t
• Mixed expression:
change during execution
− Has operands of different data types
• The syntax to declare a named constant is:
− Contains integers and floating-point
5.4 * 2 – 13.6 + 18 / 2
Evaluating Mixed Expressions • In C++, const is a reserved word
• If operator has same types of operands
− Evaluated according to the type of the operands
• If operator has both types of operands
− Integer is changed to floating-point Variable: memory location whose content may change
− Operator is evaluated during execution
− Result is floating-point
Type Conversion (Casting)
• Implicit type coercion: when value of one type is
automatically changed to another type
• Cast operator provides explicit type conversion
• Use the following form:
− static_cast <dataTypeName>(expression)
Assignment Statement
• The assignment statement takes the form:
variable = expression;
• Expression is evaluated and its value is assigned to the
variable on the left side
• In C++ = is called the assignment operator
• A C++ statement such as:
i = i + 2;
evaluates whatever is in i, adds two to it, and assigns the
new value to the memory location i
Declaring & Initializing Variables
• Variables can be initialized when declared:
int first=13, second=10;
char ch=' ';
double x=12.6, y=123.456; • --count; or count--; decrements the value of count by
• first and second are int variables with the values 13 and • If x = 5; and y = ++x; − After the second statement
10, respectively both x and y are 6
• ch is a char variable whose value is empty • If x = 5; and y = x++;
• x and y are double variables with 12.6 and 123.456, − After the second statement y is 5 and x is 6
respectively
Output
Input (Read) Statement • The syntax of cout and << is:
• cin is used with >> to gather input cout<< expression or manipulator
cin >> variable >> variable. . .; << expression or manipulator
• The extraction operator is >> << ...;
• For example, if miles is a double variable • Called an output (cout) statement
cin >> miles; • The << operator is called the insertion operator or the
− Causes computer to get a value of type double − Places it stream insertion operator
in the memory cell miles • Expression evaluated and its value is printed at the current
cursor position on the screen
Input Statement (continued) • Manipulator: alters output
• Using more than one variable in cin allows more than one • endl: the simplest manipulator − Causes cursor to move to
value to be read at a time beginning of the next line
• For example, if feet and inches are variables of type int a
statement such as: cin >> feet >> inches; Output Example
− Inputs two integers from the keyboard • Output of the C++ statement
− Places them in locations feet and inches respectively cout << a;
is meaningful if a has a value
For example, the sequence of C++ statements,
a = 45;
cout << a;
produces an output of 45
The New Line Character
• The new line character is '\n'
• Without this character the output is printed on one line
• Tells the output to go to the next line
• When \n is encountered in a string − Cursor is positioned at
the beginning of next line
• A \n may appear anywhere in the string
Examples
• Without the new line character:
cout << "Hello there.";
cout << "My name is James.";
− Would output:
Increment & Decrement Operators Hello there.My name is James.
• Increment operator: increment variable by 1 • With the new line character:
• Decrement operator: decrement variable by 1 cout << "Hello there.\n";
• Pre-increment: ++variable cout << "My name is James.";
• Post-increment: variable++ − Would output
• Pre-decrement: --variable Hello there.
• Post-decrement: variable— My name is James.
Increment & Decrement Operators (continued)
• ++count; or count++; increments the value of count
by 1
• Executable code is produced and saved in a file with the file
extension .exe.
• Declaration Statements
int a, b, c;
double x, y;
− Variables can be declared anywhere in the program, but
they must be declared before they can be used
• Executable Statements have three forms:
a = 4; //assignment statement
cin >> b; //input statement
cout << a << " " << b << endl; //output
Preprocessor Directives
statement
• C++ has a small number of operations
• Many functions and symbols needed to run a C++ program
are provided as collection of libraries
• Every library has a name and is referred to by a header file
• Preprocessor directives are commands supplied to the
preprocessor
• All preprocessor commands begin with #
• No semicolon at the end of these commands
Preprocessor Directive Syntax
• Syntax to include a header file
#include <headerFileName>
• Causes the preprocessor to include the header file iostream
in the program
• The syntax is:
#include <iostream>
Using cin and cout in a Program and namespace
• cin and cout are declared in the header file iostream, but
within a namespace named std Program Style and Form
• To use cin and cout in a program, use the following two • The Program Part − Every C++ program has a function main
statements: − Basic parts of function main are:
#include <iostream> • The heading
namespace std; • The body of the function
• The heading part has the following form
Using the string Data Type in a Program typeOfFunction main(argument list)
• To use the string type, you need to access its definition
from the header file string Syntax
• Include the following preprocessor directive: • Errors in syntax are found in compilation
#include <string> int x; //Line 1
int y //Line 2: syntax error
Creating a C++ Program double z; //Line 3
• C++ program has two parts: 1. Preprocessor directives 2. y = w + x; //Line 4: syntax error
The program
• Preprocessor directives and program statements constitute Use of Blanks
C++ source code • Use of Blanks
• Source code must be saved in a file with the file extension − One or more blanks separate input numbers
.cpp − Blanks are also used to separate reserved words and
• Compiler generates the object code − Saved in a file with identifiers from each other and other symbols
file extension .obj
• Blanks between identifiers in the second statement are • Program computes the equivalent length in centimeters
meaningless: • One inch is equal to 2.54 centimeters
int a,b,c; • Convert the length in feet and inches to all inches:
int a, b, c; − Multiply the number of feet by 12
• In the statement: inta,b,c; no blank between the t and a − Add given inches
changes the reserved word int and the identifier a into a • Use the conversion formula (1 inch = 2.54 centimeters) to
new identifier, inta. find the equivalent length in centimeters
• The algorithm is as follows:
Semicolons, Brackets, & Commas − Get the length in feet and inches
• Commas separate items in a list − Convert the length into total inches
• All C++ statements end with a semicolon − Convert total inches into centimeters − Output centimeters
• Semicolon is also called a statement terminator
• { and } are not C++ statements
Semantics
• Possible to remove all syntax errors in a program and still
not have it run
• Even if it runs, it may still not do what you meant it to do
• For example, 2 + 3 * 5 and (2 + 3) * 5 are both syntactically
correct expressions, but have different meanings
Form and Style
• Consider two ways of declaring variables:
− Method 1
int feet, inch; Main Algorithm
double x, y; • Prompt user for input
− Method 2 • Get data
int a,b;double x,y; • Echo the input (output the input)
• Both are correct, however, the second is hard to read • Find length in inches
• Output length in inches
Documentation • Convert length to centimeters
• Comments can be used to document code • Output length in centimeters
− Single line comments begin with // anywhere in the line
− Multiple line comments are enclosed between /* and */ Putting It Together
• Name identifiers with meaningful names • Program begins with comments
• Run-together-words can be handled either by using CAPS • System resources will be used for I/O
for the beginning of each new word or an underscore before • Use input statements to get data and output statements to
the new word print results
• Data comes from keyboard and the output will display on
Assignment Statements the screen
• C++ has special assignment statements called compound • The first statement of the program, after comments, is
assignment preprocessor directive to include header file iostream
+=, -= , *= , /=, and %= • Two types of memory locations for data manipulation:
• Example: x *= y; − Named constants
− Variables
Programming Example • Named constants are usually put before main so they can
• Write a program that takes as input a given length be used throughout program
expressed in feet and inches − Convert and output the length • This program has only one function (main), which will
in centimeters contain all the code
• Input: Length in feet and inches • The program needs variables to manipulate data, which are
• Output: Equivalent length in centimeters declared in main
• Lengths are given in feet and inches
Writing a Complete Program
• Begin the program with comments for documentation
• Include header files
• Declare named constants, if any
• Write the definition of the function main