c++ programming lecture 3 c++ basics – part i the hashemite university computer engineering...

33
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

Upload: elmer-wheeler

Post on 18-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

C++ ProgrammingLecture 3

C++ Basics – Part I

The Hashemite UniversityComputer Engineering

Department

(Adapted from the textbook slides)

Page 2: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 2

Outline

Introduction to C++ code. Data types. Identifiers. Casting. C++ keywords. Memory concepts.

Page 3: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 3

Sample C++ Program//Sample C++ Program/* This program prompt the user to enter two integersand return their sum*/

#include <iostream.h>

int main(){ int a1, a2, sum; cout<<"Enter the first number:"; cout << endl; cin >> a1; cout<<"Enter the second number:“ << endl; cin >> a2; sum = a1 + a2; cout <<"The sum of " << a1 << " and " << a2 << " = " << sum

<< "\n"; return 0;}

Page 4: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 4

Output

Page 5: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 5

Program Explanation I Comments:

Single line comment: after // Multi-line comments: between /* and */ Comments are not processed by the compiler, feel free to

write anything you want. Preprocessor directives:

Special instructions for the preprocessor. Start with # and usually come at the beginning of the

program. Tell the preprocessor to perform code substitutions, variables

definitions, or conditional compilation in the source code. More about this later.

.h file: Header file which is simply a library that includes the

definitions of the used functions within the program, i.e. the frequently used ones to avoid repeating the code.

Two types: standard (comes with C++ package) and user defined.

Page 6: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 6

Program Explanation II int main():

The main part of your program and it represents the entry point of it.

The compiler will compile all instructions inside the main().

So, place all instruction within the main function, i.e. between its braces { }.

{ }: Braces define a block of code. { is the start of this block and } is its end.

a1, a2, sum: Names of variables and they are called identifiers.

int: Define the data type of the used variable. int means an integer variable.

Page 7: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 7

Program Explanation III cout:

Function defined in the iostream library. An output operator. Tells the compiler to display the string or variable value

after the insertion operator << on the screen. cout is always followed by <<.

cin: An input function defined in the iostream library. Get an input usually from the keyboard. Followed by the extraction operator >> then the variable

name in which you want to store the input value. Input type depends on the variable type in which you store

the input. return 0:

Tells the compiler that the main function returns 0 to the operating system in case of successful execution of the program.

Page 8: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 8

Program Explanation IV Semicolon ; :

Tells the compiler that one instruction line has been terminated.

A large set of errors will appear if you forget to put a semicolon at the end of every code line in your program.

Any line of code terminated with ; is for the compiler, preprocessor directives do not end with ;

Page 9: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 9

C++ Versions The version is related to either the compiler or

the integrated development environment (IDE) or both of them.

Versions: Turbo C++. Borland C++. Visual C++. Visual C++.Net (simply it is a higher version of visual

C++). All compilers provide standard C++ functions,

nonstandard functions are compiler-dependent. Different operating systems have different IDEs

and different compilers.

Page 10: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 10

using Statement If you do not put .h after the library name (like

iostream library) you need to use the using statement as follows.

using: Eliminate the need to use the std:: prefix Allow us to write cout instead of std::cout To use the following functions without the std:: prefix,

write the following at the top of the programusing std::cout;using std::cin;using std::endl;

Or simply write the following line before main function:using namespace std;

Page 11: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 11

Variables Declaration To declare a variable you must specify its name

and its data type. All variables must be declared before they are

being used in the program. If you use a variable not declared the compiler will give you a syntax error.

You can place declarations in any place within your program (but make sure to be before the first usage of the variables) but it is preferred to place them at the beginning of your program.

Multiple variables of the same data type can be defined using one statement having the variables name comma separated. E.g. int a, b, c;int a = 0, b = 6, c;

Page 12: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 12

Data Types In mathematics there are different types of numbers,

e.g. real numbers, natural, fractions, integers, etc. The same concept is applied in C++, we have a

large set of data types used to define the type of the value stored in a variable.

Why we need to define the data type of a variable? The compiler needs it to know the size of memory location

that will be assigned to this variable. To define how to deal the contents of this memory location,

i.e. how to interpret it, since data is stored in memory in binary and its data type allow the computer to convert it correctly for us.

Two types of data types in C++: Fundamental or built-in data types. User defined data types.

Page 13: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 13

Fundamental Data Types -- int Integer:

Positive and negative integer values (no decimal point is allowed).

Syntax: int number; What will happen if you save a float number in an

integer? (storing 3.9 in number ignore everything after the decimal point without rounding)

The range of numbers allowed to be stored in an integer variable depends on the memory size.

short: 2 byte signed integer. long: 4 bytes signed integer. signed: the most significant bit is reserved for sign. unsigned: no negative numbers.

Page 14: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 14

Fundamental Data Types -- int

The default of int type depends on the used compiler and the operating system under which this compiler is work:

int a; // here ‘a’ is by default signed long integer under VC++ (works under windows).

int a; // here ‘a’ is by default signed short integer under Turbo C++ (works under DOS)

If you exceed the size of the variable, C++ will alter your value where this situation is called data overflow.

You cannot combine signed and unsigned for the same variable and you cannot combine long and short for the same variable.

What are the following correspond to? signed a; unsigned a; short a; short int a;

Page 15: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 15

Fundamental Data Types -- float Floating point numbers include integers, decimal

point (fractions) and exponents (power of 10). Float has decimal point precision up to 6 digits.

What happen if you enter more than 6 digits after the decimal point? (truncation)

Include both positive and negative values. Syntax: float a; Memory size: 4 bytes. Exponent must be integer, i.e. 2e2.2 is not allowed. Examples of float numbers: 1.0, 2.5, 5e2, 0.1234

Page 16: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 16

Fundamental Data Types -- double

Same as float but with greater range.

Syntax: double a; Its size is 8 bytes.

Page 17: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 17

Fundamental Data Types – char

Character is one byte of memory used to save any symbol, alphabet or digit number presented on the keyboard, e.g. :, /, @, d, 5.

Syntax: char a; char initialization:

Remember that you can initialize any variable in two ways: Either from the keyboard by the user at runtime. Or hardcoded in your program when you are writing the code.

From the keyboard: you must enter only one character. If you enter more than one character for a char variable only the first one will be taken and stored in your variable.

E.g.: What happen if you enter 199 for a character using the keyboard?

it will store 1 and ignore the rest Hard coding: only and only one character can be stored in a

char variable as follows: char t = ‘a’; or char t = ‘9’; char t = “a” // Syntax error since “a” is not only one character

Page 18: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 18

Fundamental Data Types – char Character coding is used to store the values

of characters in char variable in C++ since computer only knows binary numbers.

Based on this coding every character has a number value.

Coding types: ASCII (American Standard Code for Information

Interchange). E.g. ‘a’ has the value of 97 in ASCII.

EBCDIC (Extended Binary Coded Decimal Information Code).

Unicode : used mainly for Internet applications. ASCII is the most dominant.

Page 19: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 19

ASCII Table

Page 20: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 20

Example//Sample C++ Program, understand char concept

#include <iostream.h>

int main(){

char qq; cout<<"Enter a character"; cout << endl; cin >> qq; cout << "(int)qq is: " << (int)qq << " and " << "qq is:

" << qq; cout <<"\n"; return 0;}

Page 21: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 21

Output Example

Page 22: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 22

Fundamental Data Types -- bool Boolean value is either true or false. Size = 1 byte. Syntax: bool a; True is any non-zero value or simply true

keyword. By any non-zero value we mean:

Any number other than zero, e.g. 9, -2, -100, 3.4, etc. Any character (including white spaces) or string,

e.g. bool a = “Hello”; //will initialize a to be true. False is only zero value or false keyword. When you print a bool value on the screen, i.e.

using cout statement, it will be either 1 when true or 0 when false.

Page 23: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 23

Data Types Ranges

NameBytes

(Compiler dependent)

DescriptionRange (depends on number of

bytes)

char 1 Character or 8 bit integer.signed: -128 to 127unsigned: 0 to 255

bool 1Boolean type. It takes only two

values.true or false

short 2 16 bit integer.signed: -32768 to 32767

unsigned: 0 to 65535

long 4 32 bit integer. signed:-2147483648 to 2147483647

int 2/4

Integer. Length depends on the size of a ‘word’ used by the Operating system. In MSDOS a word is 2

bytes and so an integer is also 2 bytes.

Depends on whether 2/4 bytes.

float 4 Floating point number. --

double 8double precision floating point

number.--

Page 24: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 24

Casting

Casting is converting the data type of the value of a specified variable to another data type temporarily.

Two types of casting: Implicit casting: done by the compiler

implicitly. Explicit casting: need to be coded

explicitly by the programmer (to force casting).

Page 25: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 25

Implicit Casting While the program is compiled or during running,

you may store values of different data type from the data type of the variable you are dealing with.

In some cases, the compiler do not give you a syntax error. However, it converts the data type of the value implicitly.

Examples:bool num = 100; //implicitly the compiler will convert 100 to true

int r = 3.5; //implicitly the compiler will convert 3.5 into 3.

Note: Implicit casting is done when needed by the complier not

when needed by you.

Page 26: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 26

Explicit Casting There are special operators used for explicit

casting. Explicit casting types:

C-style explicit casting. C++ casting operators.

C-style explicit casting: Just put the data type name that you want to convert

to it before the variable name (or value) that you want to convert and place the parenthesis correctly.

Example:int a = 100;bool b = (bool)a; or bool b = bool(a);

Page 27: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 27

C++ Casting Operators There are 4 casting operators in C++, we will

take only one of them. Syntax:static_cast <new_type> (expression) Where:

new_type: is the type you want to convert to. expression: is the variable name or the expression

that you want to cast its value. Example:

int a = 100;bool b = static_cast<bool>(a);

Page 28: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 28

Notes On Casting You cast the type of the value of the

variable only. So, you do not change the original data type of the variable through casting.

Both implicit and explicit casting can cause logical errors due to possible data loss.

Page 29: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 29

Identifiers Names of variables, constants, and functions. C++ is case sensitive, i.e. letter is different

from LETTER and Letter and leTTEr. You can use anything as an identifier with the

following restrictions: Do not use any of C++ keywords, e.g. if, for, int, float,

cout, ... Never start your identifier with a digit (number) always

start it with alphabet or underscore. Do not use white spaces in your identifier, use

underscores instead. Do not use special symbols in your identifier such as

#, $, etc. Do not use any of the operators (arithmetic, logical,

etc.) in your identifier such as +, =, etc.

Page 30: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 30

C++ Keywords Words reserved by C++. Always lower case, should not be used as identifiers.

C++ Keywords

Keywords common to the C and C++ programming languages

auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords

asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t

Page 31: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 31

Memory Concepts Variable names

Correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable, it

replaces the previous value - it is destroyed, such thing is called overwriting.

Reading variables from memory does not change them

A visual representation that we will always use:

integer1 45

Page 32: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 32

Code Lines Breakage You can split a long line of code among

multiple lines by pressing enter. However, you must be careful when selecting the break locations of the line of code:

After or before an operator. After a comma in a comma separated list. After the end of a string (do not break at the middle

of a string). E.g.

cout << “Hello World\n”; //Syntax Errorcout<< “Hello World\n”; //Correct

Page 33: C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)

The Hashemite University 33

Additional Notes

This lecture covers the following material from the textbook: Fourth edition:

Chapter 1: Sections 1.20 and 1.21