Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

University of Bahrain

College of Information Technology


Department of Computer Science

CSC 103: Computer Programming for


Scientists and Engineers

Dr. Abdul Fattah Salman

Unit 2: Basic Elements of C++


CSC 103: Computer Programming for Scientists
and Engineers

These slides are based on slides of Malik


(textbook author) and modified
by Dr. Abdul Fattah Salman
A Quick Look at a C++ Program

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 3


A Quick Look at a C++ Program
(cont’d.)
• Sample run:

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 4


A Quick Look at a C++ Program
(cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 5


A Quick Look at a C++ Program
(cont’d.)
• Variable: a memory location whose contents can be
changed.

? ? ? ?

Figure 2-2 Memory allocation after the four variable declaration statements

? ? ?

Figure 2-3 Memory spaces after executing the statement length = 6.0;

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 6


A Quick Look at a C++ Program
(cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 7


The Basics of a C++ Program

• Programming language: a set of syntax rules, semantic


rules, special symbols, and reserved words.
• Syntax rules: rules that specify which statements are
legal.
– Example: In an assignment statement, only a single variable
name can appear to the left of the = sign.
• Semantic rules: rules that determine the meaning of
the statements.
– Example: In an assignment statement, the expression to the
right of the = sign is evaluated and then the resulting value
is assigned to the variable named on the left of the = sign.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 8
Special Symbols
• List of special symbols in C++ :

– From page 7 of Ray Lischner’s C++ in a Nutshell. (O’Reilly, 2003).

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 9


Reserved Words (Keywords)

• Reserved words (or keywords):


– You cannot redefine these words.
– You cannot use them for anything other than
their intended use.
Examples:
– int
– using
– return
– See Appendix A (next slide) in textbook for
complete list.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 10
Tokens
• A C++ statement can be split into tokens, which
are the smallest meaningful units of a program.
• Tokens include special symbols, reserved words,
and identifiers.
Reserved words Identifier Special symbol

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 12


Identifiers

• An identifier is the name of something in a program.


• When selecting the name of an identifier, you must
follow some rules:
– Identifiers can contain letters, Arabic digits, and underscore
character (_), but no other characters or symbols.
– Identifiers must begin with a letter or underscore (not a digit).
– You cannot use reserved words as identifiers.
• C++ is case sensitive.
– For example, number, Number, and NUMBER are three
different identifiers.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 13


Identifiers (cont’d.)
• Examples of legal identifiers:
• first
• payRate2
• Employee_Salary

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 14


Comments

• Comments are for the reader, not the compiler.


• Two styles:
– Single-line comments begin with //
// This is a C++ program.
// Welcome to C++ Programming.
– Multiple-line comments are enclosed between /* and */
/*
You can include comments that span
several lines.
*/

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 15


Whitespace

• Every C++ program contains whitespace.


– Includes blanks, tabs, and newline characters.
• Whitespace must separate reserved words and
identifiers from each other.
• Proper use of whitespace (such as indenting)
also makes programs more readable.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 16


Declaring Variables

• Before you can use a variable in a program, you


must declare it, using statements such as

double length;
int num1;

• These statements say that: in this program I will


use a variable named length whose data type is
double, and I’ll use a variable named num1 whose
data type is int.
Data Types

• Data type: is a set of values together with a


set of allowed operations on those values.
• C++ data types fall into three categories:
– Simple data types
– Structured data types
– Pointers
• For the next few weeks we’ll mostly use
simple data types.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 18


Partial Hierarchy of Data Types

Data Types

Simple Data Structured


Pointers
Types Data Types

Integral
Floating-Point
(int, bool, Enumeration
(double, …)
char, …)
Simple Data Types

• Three categories of simple data type:


– Integral: integers (numbers without a decimal point).
– Unsiged: char, short, int, long,
long long
– Signed: bool, unsigned char, unsigned
short, unsigned int, unsigned long
– Floating-point: (numbers with a decimal point).
– float, double, long double
– Enumeration type: programmer-defined data type.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 20


int Data Type

• Examples of int data:


-6728
0
78
+763
• Do not use commas within numbers. Typing 1,430
instead of 1430 will usually cause an error.
• Range of possible values: -231 to 231 - 1
-2147483648 to +2147483647

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 21


bool Data Type

• The bool type has only two possible values:


true and false.
– It’s useful for keeping track of true/false (Boolean)
information, such as whether a person’s age is
greater than 21 or not.
• This is considered an integral data type
because it’s actually implemented as a 0 for
false and a 1 for true.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 22


char Data Type

• Used for single characters: letters, digits, and other


keyboard symbols.
• Each character is enclosed in single quotes:
– 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a perfectly good character.
– Written ' ', with a space left between the single quotes.
• The char data type is considered an integral data type
because it’s actually implemented as an integer
between 0 and 255, using a code called extended
ASCII code (next slide).
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 23
char Data Type (cont’d.)

• ASCII: American Standard Code for Information


Interchange
– Each of 256 integer values (from 0 to 255) represents a
different character.
– For example, the ASCII code for 'A' is 65 and the ASCII
code for 'd' is 100.

– For complete list, see Appendix C in textbook (next slide).

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 24


This is a
blank space.
Floating-Point Data Types

• Floating-point data types (float, double, and


long double) are used for non-integer numbers,
i.e., numbers that contain a decimal part.
• We’ll generally use double when we want a floating-
point number.
• Examples of double data:
-67.28
78.1
+763.345

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 26


Floating-Point Data Types (cont’d.)

• Floating-point numbers can be entered or displayed


using decimal notation or using a modified scientific
notation.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 27


Review: Partial Hierarchy of Data Types

Data Types

Simple Data Structured


Pointers
Types Data Types

Integral
Floating-Point
(int, bool, Enumeration
(double, …)
char, …)
string Type

• A string is a sequence of zero or more characters


enclosed in double quotation marks, such as "Hello
there."
– Contrast with char data type, which is a single character
inside single quotation marks.
• Unlike the data types discussed before, the string data
type is not built into the core C++ language. It’s defined
in something called the C++ Standard Library. So a
program that uses strings must have the following line:
#include <string>

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 29


Arithmetic Operators

• Some C++ arithmetic operators:


• + addition
• - subtraction
• * multiplication
• / division
• % modulus (or remainder)
• You can use +, -, *, and / with integral and floating-
point data types.
• You can use % only with integral data types.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 30


Arithmetic Expressions

• Arithmetic expressions combine arithmetic operators


and operands (values) to yield a result.
• Example: 12.8 * 17.5 - x
• This example contains two operators and three operands.

• Arithmetic expressions can be:


– Integral expressions: all operands are integers.
– Floating-point expressions: all operands are floating-point.
– Mixed expressions: some operands are integer, some are
floating-point.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 31
Integral Expressions

• An integral expression is an arithmetic expression in


which all operands are integers. It yields an integer
result.
– Example: 2 + 3 * 5

– Caution: When you use / with integers, the integer


result is truncated (no rounding).
– Example: 7 / 2 yields a result of 3

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 32


Quotient and Remainder
• We know that, mathematically, 7 ÷ 2 = 3.5
• Recall that another way of looking at it is to say that
7 ÷ 2 is equal to 3 with a remainder of 1.
• In this example, 3 is called the quotient and 1 is
called the remainder.
• In C++, using the / operator with integers yields the
quotient.
• Example: In C++, 7 / 2 yields a result of 3
• And using the % operator with integers yields the
remainder.
• Example: In C++, 7 % 2 yields a result of 1
Floating-Point Expressions

• A floating-point expression is an arithmetic


expression in which all operands are floating-point.
It yields a floating-point result.
– Example: 7.0 / 2.0
• The expression above yields 3.5
– We could have typed 7. instead of 7.0, because 7. is
treated as a floating-point number (but 7 is treated as an
integer).

– Another example: 12.8 * 17.5 - 34.52

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 34


Operator Precedence and
Associativity
• C++ obeys the same “order-of-operations” rules that
you learned in math classes:
• Operators inside parentheses are evaluated first.
• *, /, and % have the same level of precedence and are
evaluated next.
• + and – have the same level of precedence and are
evaluated next.
• Arithmetic operators of the same level of precedence
are performed from left to right. (We say they have
“left-to-right associativity.”)
• Example: Evaluate the following expression:
3 * 7 - 6 + 2 * 5 / 4 + 6
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 35
Mixed Expressions

• A mixed expression is an arithmetic expression that


has some integer operands and some floating-point
operands.
• Examples:
2 + 3.7
6 / 4 + 3.9
5.4 * 2 - (3.6 + 5) / 2
• See next slide for rules on how C++ evaluates these.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 36


Mixed Expressions (cont’d.)

• Evaluation rules:
– The precedence and associativity rules from above
still apply.
– If an operator’s operands are of the same type
(both integer or both floating-point):
• The result is the same type as the operands.
– If an operator has both types of operands:
• Integer is “promoted” to floating-point.
• The operation is performed.
• The result is floating-point.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 37
Type Conversion and Casting

• Implicit type conversion (also called coercion) occurs


when C++ automatically changes a value of one data
type to another data type. We’ve seen some examples
of this with mixed expressions:
– To perform 2 + 3.7, first converts the 2 from an
int to a double.
• C++ also lets you perform explicit type conversion
using the cast operator:
static_cast<dataTypeName>(expression)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 38


Type Conversion (Casting) (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 39


Truncating Versus Rounding
• Note that when C++ converts a floating-point
number to an integer, it truncates rather than
rounds.
• Example: static_cast<int>(7.01) and
static_cast<int>(7.99) both give 7.

• Often we want to round to the nearest integer. At


several points (such as on p. 159) the book uses a
standard trick to do this: add 0.5 to your floating-
point number before you cast it to integer.
• Example: static_cast<int>(7.01 + 0.5)
gives 7 but static_cast<int>(7.99 + 0.5 )
gives 8.
Unary Versus Binary Operators

• The arithmetic operators we’ve discussed are all


binary operators: they take two operands.
• Some operators are unary operators (one operand).
• In fact, + and – can be either binary or unary,
depending on the context.
• Unary – is negation.
• Example: -2 * 3
• Another example: -2 * +3

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 41


Other Operators

• As well as the arithmetic operators discussed above,


C++ has many other operators.
• See Appendix B (next slide) in the textbook for a
complete list that shows precedence and associativity
of all the operators.
– Note from this list that unary + and – have higher
precedence than binary + and – .
• Unfortunately the table in Appendix B contains a few
typos, so be sure to fix them using the list of textbook
typos on the course website.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 42
Variables

• The expressions we’ve looked at above used constant


numeric values.
– Example: 2 * 3.5
• In most programs you’ll also use variables, which are
named memory locations whose values may change
as the program runs.
– Example: 2 * payRate
• When naming your variables, be sure to follow the
rules listed earlier for identifiers.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 44


Declaring Variables

• In C++ you must declare each variable’s name before


you can use the variable.
• Syntax to declare one or more variables:

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 45


Putting Data into Variables

• A variable is said to be initialized the first time you


place a value into it.
• A variable that has not been initialized will hold an
unpredictable “garbage” value. Visual Studio gives an
error message if you use an uninitialized variable in
an expression.
• There are two ways for placing data into a variable :
– Using an assignment statement.
– Using an input (read) statement to let the user enter a
value from the keyboard.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 46


Assignment Statement

• The assignment statement takes the form:

• The expression on the right side is evaluated and its


value is assigned to the variable on the left side.
• Examples:
dailyRate = 0.0002;
annualRate = 365 * dailyRate;
• In C++, = is called the assignment operator.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 47


Assignment Statement (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 48


Declaring & Initializing Variables

• You can use the assignment operator to initialize a


variable in the same statement that declares it.
• Examples:
int first = 13, second = 10;
char ch = ' ';
double x = 12.6;

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 49


Assignment Versus Equality

• The = operator in C++ has a different


meaning from the meaning it has in your
math classes.
• Example: in a math class, the following
statement cannot be true:
x = x + 1;
• But this is a perfectly good (and
frequently used) C++ statement. It tells
the program to increase x’s value by 1.
Increment and Decrement Operators

• The increment operator ++ increases a variable by 1.


– Example: The statement
++x;
does the same thing as the statement
x = x + 1;
• Similarly, the decrement operator -- decreases a
variable’s value by 1.
– Example: The statement
--x;
does the same thing as the statement
x = x - 1;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 51
Pre- and Post-Increment/Decrement
• These operators behave differently depending on whether they’re
placed before or after the variable name.
– Pre-increment ++variable Increments the variable, and then uses the
incremented value in the expression.
– Post-increment variable++ Uses the variable’s original value in the
expression, and then increments the variable.
• What is the difference between the following?
• x=6 y=5
x = 5; x = 5;
y = ++x; y=6 y = x++; x=6

• Similarly for pre-decrement (--variable) and post-decrement


(variable--).
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 52
Input (Read) Statement
• In an input statement (or read statement) , cin is used with >> to let
the user enter a value into one or more variables.

• The operator >> is the stream extraction operator.


• Example, if miles is a double variable, the following statement gets
a value of type double from the keyboard and places it in the variable
miles: cin >> miles;

• A single input statement can assign values to more than one variable.
– Example: if feet and inches are variables of type int, the
following statement reads two integers from the keyboard and
places these integer values in feet and inches respectively:
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 53
Prompt Lines
• cin >> feet >> inches;
– cin >> feet;
cin >> inches;
• A prompt line is a cout statement that tells the user what to
do. Example:
cout << "Please enter a number between 1 and 10 and "
<< "press the return key." << endl;
cin >> num;

• You should always include a correctly spelled, properly


punctuated prompt line when you want the user to enter some
input.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 54


Output Statement

• In an output statement, cout is used with << to


display text or values on the screen:

• The operator << is the stream insertion operator.


• The expression is evaluated and its value is
printed at the current cursor position on the screen.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 55


Manipulators in Output Statements

• You can use manipulators to format the output.


– Example: the manipulator endl causes the cursor to move
to beginning of the next line.

– We’ll study some other manipulators in Chapter 3.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 56


Escape Sequences in Output
Statements
• Escape sequences are another way to format output.
Example: The new line character is '\n'
cout << "Hello there.";
cout << "My name is James.";
Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";
Output :
Hello there.
My name is James.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 57


Escape Sequences in Output
Statements (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 58


The Standard Library

• The core C++ language has a relatively small number


of built-in operations.
• Many other useful operations are provided as a
collection of files called the C++ Standard Library.
• These library files make your job easier, because they
save you from having to re-invent the wheel when
you want to perform common tasks.
• A big part of becoming a C++ programmer is learning
about the many library files in the Standard Library.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 59


The Standard Library (cont’d.)

• Each library file (or “header file”) has a name, which


is typically written inside angle brackets.
– Examples:
• <iostream>
• <string>
• <cmath>
• The next slides show how to tell the compiler that
you want to use operations from one or more of these
files.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 60


Preprocessor Directives

• Most programs contain


preprocessor directives.
These are commands
that the preprocessor
program executes before
your source code is
compiled.
• All preprocessor
directives begin with #,
and they do not end with
a semicolon.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 61
The #include Directive

• The most common preprocessor directive is


#include, which tells the compiler that you want to
use a Standard Library file.
• Syntax to include a header file:

• For example:
#include <iostream>
– Causes the preprocessor to include the header file
iostream in the program. Without this, you could not use
cout or cin in your program.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 62
namespace and Using cin and cout in
a Program
• cin and cout are declared in the header file
iostream within the std namespace.
• To use cin or cout in a program, use the following
two statements:
#include <iostream>
using namespace std;
• Without the using statement, you would need to
type std::cin instead of just cin throughout
your program.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 63


Using the string Data Type in a Program

• Recall that the string data type is not built


into the core C++ language. It’s defined in the
C++ Standard Library.
• To use the string data type in a program, you
must access its definition from the header file
<string>, using the following preprocessor
directive:
#include <string>

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 64


The main Function

• A function is a named block of code that


performs a well-defined task.
• Every C++ program must contain a function
named main. This is where execution begins
when you run the program.
• Complex programs contain many functions,
but for now most of your programs will only
contain the main function.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 65


The main Function (cont’d.)

• The first line of a


function is called
the function’s
heading:
int main()
• The statements
enclosed between
the curly braces
{ and } form the
function’s body.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 66
Named Constants

• A named constant is a memory location whose


content cannot change during execution.
• Syntax to declare a named constant:

• By convention, we use all upper-case letters for


constant identifiers.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 67


Syntax Errors

• Syntax rules : indicate what is legal and what is not


legal.
– Example of a syntax rule: Every C++ statement
must end with a semicolon.
• The compiler finds and reports syntax errors during
compilation. It won’t let you run the program until
you fix these errors.
int x; //Line 1
int y //Line 2: Syntax error

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 68


Semantic Errors

• Semantic rules : set of rules that defines meanings to


language constructs.
• A program with no syntax errors may compile and
run but may still not produce correct results.
• Example: 2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but have
different meanings. So if you use one of these
expressions where you should use the other one, your
program will produce incorrect results.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 69


Documentation

• A program is easier to understand and modify if it is


well-documented.
• Two keys to good documentation:
1. Use comments.
2. Choose meaningful variable names.
• Comments should:
– Explain the purpose of the program.
– Identify who wrote it, and when.
– Explain the purpose of particular statements whose
meaning is not obvious.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 70
Documentation (cont’d.)

• Variable names should be self-documenting:


– Example: use length instead of x.

• Avoid run-together words, such as annualsale.


This is hard to read.
– Solutions:
• Use “camel notation”: capitalize the 1st letter of each
new word: annualSale
• Insert an underscore just before a new word:
annual_sale

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 71


Compound Assignment Statements

• In addition to the simple assignment operator =, C++


provides several compound assignment operators,
including:
+= -= *= /= %=
• Simple assignment statement:
x = x * y;
• Equivalent compound assignment statement:
x *= y;
• You don’t need to use them in your own programs,
but you must understand what they mean.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 72

You might also like