ES 036 Programming Fundamentals

Download Report

Transcript ES 036 Programming Fundamentals

ES 036
Programming
Fundamentals
C++ Basics
[email protected]
www.eng.uwo.ca/people/reagleson
Dr. Roy Eagleson
Converting C++ programs in to
machine language
Text Editor
 Preprocessor
 Compiler
 Linker
 Loader

20-Jul-15
ES036 QMR/RE
2
Converting C++ in to machine language

Text Editor
 The
program is written using the text editor is
known as source code.
 The source code (human readable instructions)
is saved on to the secondary storage section of
the computer system (disk) with an extension
‘.cpp’ to let the compiler know that it is written in
C++ language.
 The source code needs to be grammatically
correct
20-Jul-15
ES036 QMR/RE
3
Converting C++ in to machine language

Preprocessor: A program that modifies the source
code by adding other files and performing various
text replacements
 It executes automatically before the translation period
starts.
 Examples:
 #include <iostream> adds a file called a header file
to the source code. It contains, among other things,
the prototypes for cin and cout functions.
 #define PI 3.141593 replaces all instances of PI in a
program with 3.141593.
 Compilation (step 3) follows immediately after the
preprocessing, so, none can access the modifications
made by the preprocessor
20-Jul-15
ES036 QMR/RE
4
Converting C++ in to machine language

Compiler translates preprocessed source
code into an object code that contains
machine readable instructions
 The object code is saved on to the disk by the
compiler with an extension ‘.obj’ along with
the same source-code name
 This file is basically a binary file
20-Jul-15
ES036 QMR/RE
5
Converting C++ in to machine language

Linker:





scans the standard library,
selects the needed function (precompiled) and
upon linking them into the object file, produces an
executable file with extension ‘.exe’ (for UNIX based
system it is ‘.out’) and stores it on to the disk.
Libraries are a collection of functions/objects
Examples:


20-Jul-15
The linker adds the precompiled (in binary form)
function definitions for cin, cout, etc.
If one separates his program into more than one source
file, the object code for each source file is added.
ES036 QMR/RE
6
Converting C++ in to machine language

Loader: The loader places the executable
file on to the primary storage location
(RAM) of the computer system, from
where the CPU executes the program,
instruction by instruction
20-Jul-15
ES036 QMR/RE
7
Converting C++ in to machine language
Text Editor
/* hello.cpp */
#include <iostream>
int main()
{
cout<<"hello world\n";
return 0;
}
Preprocessor adds iostream text
(prototype for cout)
Compiler converts to machine code
hello.obj
Object code
Linker
-add library
-add cout object code
-add object code for
other functions
hello.exe
Loader copies file to RAM
and CPU executes the
program when the icon is
double-clicked, for example
Program Example
20-Jul-15
Executable
image
ES036 QMR/RE
8
Converting C++ in to machine language

Integrated Development Environment (IDE)
program:
 It
manages all the previously discussed steps and
combines an editor, compiler, linker and debugger
into a single development environment.
 Advantage: all the pieces are designed to work
together; for example, if the compiler detects an error,
the system is switched to the editor with the file
positioned at the problem line.

Debugger: The debugger locates the problem in
the program during the compilation time
20-Jul-15
ES036 QMR/RE
9
//The first C++ Program
#include <iostream> //preprocessor directive
using namespace std; //”using” directive
// entry point
int main()
//first function called in C++
{// function body begins with curly bracket
cout << “Hello world!"; /* printing a string on the
standard output*/
return 0; /*represents successful termination of
the program*/
} // function body ends with curly bracket
20-Jul-15
ES036 QMR/RE
10
Comments in C++



Comments allow us to put some descriptions in our
code
Compiler completely ignores them
// this is a comment
 Starting

from ‘//’ to the end of the line
/* this is also a comment */
 Everything
between ‘/*’ and ‘*/’
 a = b /* comment inside a statement */ + c;
20-Jul-15
ES036 QMR/RE
11
Preprocessing Directive




The line begins with ‘#’ characters are known as
preprocessor directives.
#include <iostream> causes the preprocessor to
include a copy of the standard input /output file
iostream (this is a C++ system file)
The angle bracket indicates that this file is
available at a system dependent place.
The iostream file contains information on the
function cout used in the program
20-Jul-15
ES036 QMR/RE
12
Function main


Every C++ (and C) program executes its instructions
from the function called main. This is the first
function, called in C++ environment.
Any function in C++ has a prototype as,
Return_data_type Function_name (Argument_list_with_data_types)

According to the prototype, the main function returns
an integer (int) type value without taking any
argument to process. Note: one can use (optional)
the keyword void inside the parentheses as int
main(void), to represent that the function takes no
argument.
20-Jul-15
ES036 QMR/RE
13
Curly Brackets
The left curly bracket begins the body of each
function
 This right curly bracket ends the body of each
function.
 A function definition looks like the following:

Return_data_type Function_name(Argument_list_with_data_types)
{
Body of the function;
}
20-Jul-15
ES036 QMR/RE
14
Producing Output With cout

cout
 is
an ostream object
 streams output to standard output
 uses the << (output) operator

General Form:
 cout

<< expression << expression;
Note: An expression is any C++ expression
(string constant, identifier, formula or function
call)
20-Jul-15
ES036 QMR/RE
15
return 0
return is a keyword for C++ (and C)
programming language
 A returned zero value is interpreted as
successful termination of the program.
 Non-zero values are interpreted as
unsuccessful termination

20-Jul-15
ES036 QMR/RE
16
Good Programming Approach

Purpose of a program
 it
presents the computer with a set of instructions and
 it provides the programmer a clear, easy to read
description of what it does.
 The goal of a programmer
 Create
a simple and easy to read programs.
 Make the program as clear, concise and simple as
possible
20-Jul-15
ES036 QMR/RE
17
Good Programming Approach





Comment the program
Pick meaningful names for the variables
Indentation
Clarity
Simplicity
 Do not write a long function
 Avoid complex logics
 Write many short statements instead of a very long
one
 Make the program as simple and easy to understand
as possible
20-Jul-15
ES036 QMR/RE
18
C++ Variables (Objects)




Variables are boxes that can hold things
Each box has a name (“identifier”)
Size of the box depends on the “type” of things
you are planning to put there
You have to tell the compiler in advance
(“declare”),
 Names
of each of the boxes you want
 The type of things that will go in each box
20-Jul-15
ES036 QMR/RE
19
Why Use Types
Computer sees everything in 1’s and 0’s
 “Type” is how we interpret these patterns
 What is 1101101?
 Integer (int): it is 109
 Character (char): it is ‘m’
 Floating point (float): it is 1.53x10-43

20-Jul-15
ES036 QMR/RE
20
Declaring Objects
Type








Tell the compiler in
advance

Types
Names

Names can have A-Z, az, 0-9 and ‘_’
Case sensitive
Cannot start with a digit
Cannot be a reserved
word
20-Jul-15




Name
int alice;
float bob, chad;
int alice = 10;
int alice(10);
float bob, chad =
2.4;
float bob(1.5),
chad(2.4);
Element atom;
ES036 QMR/RE
21
Identifier
sum
Box
Built in type
75
Holds int type objects
Size is 32 bits (4 bytes)
Identifier
Outer box
atom
Na
User defined type
11
Inner boxes
22.989770
Holds Element type objects
Size is 10 bytes
20-Jul-15
ES036 QMR/RE
22
Some Built In Types
Data Type Range of Values
Size
char
-128 to 127
1 byte
int
-2,147,483,648 to 2,147,483,647
4 bytes
float
6 Digits of Precision
±3.402823x10±38
15 Digits of Precision
± 1.797693x10±308
True or False
4 bytes
double
boolean
20-Jul-15
ES036 QMR/RE
8 bytes
1 byte
23
Mixing types:

avg = (a + b)/2;
 avg,

a and b must be same type
Exception
 It
is OK to mix numerical types
 i.e. int, float, double
 Be
20-Jul-15
careful not to loose precision
ES036 QMR/RE
24
C++ Reserved Words
asm, auto, bool, break, case, catch, char, class,
const, const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false,
float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof,
static, static_cast, struct, switch, template, this, throw, true,
try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while
20-Jul-15
ES036 QMR/RE
25
Where to Declare

Immediately prior to use
int main()
{
…
int sum;
sum = a + b;
…
return 0;
}
20-Jul-15

At the beginning
int main()
{
int sum;
…
sum = a + b;
…
return 0;
}
ES036 QMR/RE
26
C++ Statements




One C++ instruction
that ends with a
semicolon
Can take more than
one line
Declaration
statements
Assignment
statements
20-Jul-15
int sum(0), a(5),
b(10);
sum = a + b;
float temp_c(0);
float temp_f(78);
temp_c = (temp_f –
32)*5/9;
ES036 QMR/RE
27
Compound Statements


Use { and } to group
any number of
statements
This block is treated
as one statement
20-Jul-15
{
cout << “Hello”;
return 0;
}
ES036 QMR/RE
28
Concepts Presented So Far
How to write a simple C++ program?
 What is a variable?
 How to tell the compiler what variables I
want?
 What is a C++ statement?

20-Jul-15
ES036 QMR/RE
29
#include <iostream>
using namespace std;
// entry point
int main()
{
float w_lb, w_kg;
Pre-processor directives
“using” directives
main: single C++ statement !
A declaration statement
cout << "Enter weight (lb): ";
cin >> w_lb;
An assignment statement
w_kg = w_lb * 0.454;
cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
20-Jul-15
ES036 QMR/RE
30
#include <iostream>
// without “using namespace std;”
// entry point
int main()
{
float w_lb, w_kg;
std::cout << "Enter weight (lb): ";
std::cin >> w_lb;
w_kg = w_lb * 0.454;
std::cout << “Weight is " << w_kg << “kg\n";
return 0;
} // end function main
20-Jul-15
ES036 QMR/RE
31
Symbolic Constants






Objects that won’t let you change the initial value
So, they must be given a value in its declaration
As a matter of style, names are all caps
E.g. const double PI = acos(-1.0);
Always use to these to represent numeric values
within your program
Or for anything that you know will not change
20-Jul-15
ES036 QMR/RE
32
Calculating Things
Using calculator
 4-2+5-1 = ?
 +, - *, / and = are the operators
 3+2*5 vs (3+2)*5
 Need to consider operator precedence
 * and / have higher precedence than +,  C++ operators have these and more

20-Jul-15
ES036 QMR/RE
33
C++ Operators

Operators take one or more input values
and produce one output value
 E.g.

+ , - , * , / , < , > , <= , >= , && , ||
Operators come in three flavours
operators – take one input value
 Binary operators – take two input values
 Ternary operators – take three input values
 Unary
20-Jul-15
ES036 QMR/RE
34
C++ Operator Map
Operators
Binary
Arithmetic
+ - add
- - sub
* - mul
/ - div
% - mod
20-Jul-15
Logical
&& - and
|| - or
Unary
Bitwise
& - and
| - or
^ - xor
Copy
=
+=, -=, *=, /=, %=
&&=, ||=, &=, |=, ^=
Comparison
< - less-than
> - gt.-than
<= - less-or-eq
>= - gt-or-eq
== - equal
!= - not-equal
ES036 QMR/RE
Arithmetic
- - negate
++ - increment
-- - decrement
Logical
! - negate
Bitwise
~ - negate
Pointer * , &
35
Unary Operators
int a(9);
Negate: -a gives -9
 Logical-invert: !a gives 0
 * and & are pointer operations (discussed
later)
 Increment: ++
 Decrement: -
20-Jul-15
ES036 QMR/RE
36
More Unary Expressions
int a(9), b;

Pre-Increment :
b

= a++;
b is 9 and a is 10
Pre-Decrement :
b

b is 10 and a is 10
Post-Increment:
b

= ++a;
= --a;
b is 8 and a is 8
Post-Decrement:
b
20-Jul-15
= a--;
b is 9 and a is 8
ES036 QMR/RE
37
Arithmetic Operators: + - * / %
a+b, a-b, a*b, a/b
 Integer division: 11/4 gives 2


Floating point division:
 11.0/4

gives 2.75
Modulo operator: % (only for integers)
 11%4
gives 3
 10%5 gives 0
20-Jul-15
ES036 QMR/RE
38
Copy Operator (Assignment operator)

Simple copy: a = b;
 Overwrites
the left object (l-value) with the
result of the expression on the right (r-value)
 l-value must be writable

Copy with add
a

+= b; is the same as a = a + b;
Other copy-with-subtract, multiplication,
division behaves the same
a
20-Jul-15
-= b; a *= b; a /= b; etc
ES036 QMR/RE
39
Comparison Operators

< , > , =<, =>, ==, !=
 All
yield Boolean true (1) or false (0)
11<4 is false. 11<11 is false
 11>4 is true. 11>11 is false
 11>=11 and 11<=11 both are true
 4==4 is true. 4!=4 is false

 Don’t
20-Jul-15
use floating-point values with == or !=
ES036 QMR/RE
40
Logical Operators

Logical AND: &&
 exp1
&& exp2 && exp3 && exp3
 Yields true if all the expressions are true
 If an expression is false, skips the rest

Logical OR: ||
 exp1
|| exp2 || exp3 || exp3
 Yields true if any expression is true
 If an expression is true, skips the rest

These are called “short-circuit” operators
20-Jul-15
ES036 QMR/RE
42
Examples of Logical Operators


(-6<0)&&(12>=10)
true && true
results in true
(3.0 >= 2.0) || (3.0 >= 4.0)
true || false
results in true
true && false
 (3.0 >= 2.0) && (3.0 >= 4.0)
results in false
20-Jul-15
ES036 QMR/RE
43
Expressions

A series of operators
and their inputs
 E.g.



x+3-y+5
Evaluated from left-toright
Be careful with
division
Pay attention to
operator precedence
20-Jul-15
x3
4

5
y 3
is not the same as
x  3/ 5  4/ y  3
Correct form:
(x+3)/5 + 4/(y+3)
ES036 QMR/RE
44
Operator Precedence
Use parenthesis if you are not sure!
 Unary (++, --, !, -)
 Arithmetic (*, /, %, +, -)
 Comparison (< , <= , > , >=, ==, !=)
 Logical (&&, ||)
 Assignment (= , +=,-=,*= ,/= ,%=, etc)

20-Jul-15
ES036 QMR/RE
45
Expression Examples

2*x*x-3*y/5*y+6

Should really be
 2*x*x-(3*(y/5)*y)+6

(2*x*x-3*y)/(5*y+6)
20-Jul-15
ES036 QMR/RE
3y
2x 
y6
5
2
2x  3y
5y  6
2
46
Expressions With Side Effects
r
r
r
x


=
=
=
=
x + y--;
x + y; y
++x - y;
x+1; r =
is equivalent to
= y-1; (two actions!)
is equivalent to
x - y; (two actions!)
Keep it simple
 Not
20-Jul-15
r = --x + y++;
ES036 QMR/RE
47
Using Standard Utilities
C++ compilers comes with a vast
collection of utilities: i/o, math etc
 This is called the “standard library”
 You need to:

 Include
proper header files. E.g.
#include<iostream>
 Use using namespace std; statement
 Or use std:: prefix
20-Jul-15
ES036 QMR/RE
48
Standard Input and Output

Called the i/o stream objects
 #include
<iostream>
Input is usually from keyboard
 Output is usually to a console window
 cout object is the output stream (ostream)
 cin object is the input stream (istream)

20-Jul-15
ES036 QMR/RE
49
Producing Output With cout

cout
 is
an ostream object
 streams output to standard output
 uses the << (output) operator

General Form:
 cout

<< expression << expression;
Note: An expression is any C++ expression
(string constant, identifier, formula or function
call)
20-Jul-15
ES036 QMR/RE
50
//Example1 for input and output
#include <iostream>
#include <string>
1
using namespace std;
2
int main()
4.5
{
output
int i, j;
1,2,
double x;
4.5 cm
string units = “ cm”;
cin >> i >> j;
cin >> x;
cout << “output \n”;
cout << i << ‘,’ << j << ‘,’ << endl
<< x << units << endl;
return 0;
} // Input stream:
20-Jul-15
ES036 QMR/RE
51
Changing cout behaviour

Use setf() and unsetf() to set following attributes
 E.g.
cout.setf(ios::scientific);
Flag
ios::showpoint
Meaning
ios::fixed
fixed decimal notation
display the decimal point
ios::scientific scientific notation
20-Jul-15
ios::right
right justification
ios::left
left justification
ES036 QMR/RE
52
cout Precision and justification

With #include <iomanip> you can use
 setw(n)

and setprecision(n)
E.g.
cin >> n;
cout << setprecision(4)
<< “Sqrt with 4 digits: ” << sqrt(n)
<< endl << “Sqrt right justified: ”
<< setw(10) << sqrt(n) << endl;
20-Jul-15
ES036 QMR/RE
53
Characters and input with cin



>> discards leading whitespace
get() method is used to input whitespace
characters
45
Example:
c
int x;
char y;
cin >> x >> y;
cin >> x;
cin.get(y);
20-Jul-15
39
b
x: 45
y: ‘c’
x: 39
y: ‘\n ’
ES036 QMR/RE
54
Math Functions with <cmath>
abs(x)
computes absolute value of x
sqrt(x)
computes square root of x, where x >=0
pow(x,y) computes xy
ceil(x)
nearest integer larger than x
floor(x) nearest integer smaller than x
exp(x)
computes ex
log(x)
computes ln x, where x >0
log10(x) computes log10x, where x>0
20-Jul-15
ES036 QMR/RE
55
Trigonometric Functions
sin(x)
sine of x, where x is in radians
cos(x)
cosine of x, where x is in radians
tan(x)
tangent of x, where x is in radians
asin(x)
sine-1(x), returns angle in radians [-π/2, π/2]
acos(x)
cosine-1(x), returns angle in radians [0,π]
atan(x)
tan-1(x), returns angle in radians [-π/2, π/2]
atan2(y,x)
tan-1(y/x), returns angle in radians [-π, π]
sinh(x)
Hyperbolic sine of x
cosh(x)
Hyperbolic cosine of x
tanh(x)
Hyperbolic tan of x
20-Jul-15
ES036 QMR/RE
56
Now you can …


Create a simple project in Visual Studio
Write C++ code that contains
 Getting
user input
 Displaying information
 Complex calculations



Compile and run above C++ code
Make it work!
Answer questions at the end of chapter 2
20-Jul-15
ES036 QMR/RE
57
Next Step
Chapter 3
 Control Structures

 if-else
statements
 switch statements
 while and do-while loops
 for loops
 break and continue statements
20-Jul-15
ES036 QMR/RE
58