You are on page 1of 33

C++ Programming Lecture 3

C++ Basics Part I

The Hashemite University Computer Engineering Department
(Adapted from the textbook slides)


Introduction to C++ code. Data types. Identifiers. Casting. C++ keywords. Memory concepts.
The Hashemite University 2

Sample C++ Program

//Sample C++ Program /* This program prompt the user to enter two integers and return their sum*/
#include <iostream.h>

int main() { int unsigned a1, a2, sum; cout<<"Enter the first number:"; //this message will appear to the user 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; }
The Hashemite University 3


The Hashemite University

Program Explanation I


Preprocessor directives:

Single line comment: after // Multi-line comments: between /* and */ Comments are not processed by the compiler, feel free to write anything you want.
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.
The Hashemite University 5

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. Names of variables and they are called identifiers. Define the data type of the used variable. int means an integer variable.
The Hashemite University 6

a1, a2, sum:


Program Explanation III



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 <<.
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. Tells the compiler that the main function returns 0 to the operating system in case of successful execution of the program.
The Hashemite University 7

return 0:

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 ;
The Hashemite University 8

C++ Versions

The version is related to either the compiler or the integrated development environment (IDE) or both of them. Versions:

All compilers provide standard C++ functions, nonstandard functions are compiler-dependent. Different operating systems have different IDEs and different compilers.
The Hashemite University

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

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 program using std::cout; using std::cin; using std::endl; Or simply write the following line before main function: using namespace std;
The Hashemite University 10

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;
The Hashemite University 11

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?

Two types of data types in C++:

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. Fundamental or built-in data types. User defined data types.

The Hashemite University


Fundamental Data Types -- int


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 bytes signed integer. long: 4 bytes signed integer. signed: the most significant bit is reserved for sign. unsigned: no negative numbers.
The Hashemite University 13

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;
The Hashemite University 14

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
The Hashemite University 15

Fundamental Data Types -double

Same as float but with greater range. Syntax: double a; Its size is 8 bytes.

The Hashemite University


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:

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.

Either from the keyboard by the user at runtime. Or hardcoded in your program when you are writing the code.

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

Hard coding: only and only one character can be stored in a char variable as follows:

it will store 1 and ignore the rest

char t = a; or char t = 9; char t = a // Syntax error since a is not only one character
The Hashemite University


Fundamental Data Types char

Character coding is used to store the values of characters in char variable in C++ since computers 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.
The Hashemite University 18


The Hashemite University


//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; }

The Hashemite University


Output Example

The Hashemite University


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:

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.
The Hashemite University 22

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.

Data Types Ranges

Name Bytes (Compiler dependent) 1 1 2 4 Description Range (depends on number of bytes) signed: -128 to 127 unsigned: 0 to 255 true or false signed: -32768 to 32767 unsigned: 0 to 65535 signed:-2147483648 to 2147483647 char bool short long Character or 8 bit integer. Boolean type. It takes only two values. 16 bit integer. 32 bit integer. 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. Floating point number. double precision floating point The Hashemite University number.



Depends on whether 2/4 bytes.

float double

4 8



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).
The Hashemite University 24

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.


Implicit casting is done when needed by the complier not when needed by you.
The Hashemite University 25

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);
The Hashemite University 26

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.

int a = 100; bool b = static_cast<bool>(a);
The Hashemite University 27

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.

The Hashemite University



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.
The Hashemite University 29

C++ Keywords

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

C++ Ke yw o rd s
Keywords common to the C and C++ programming languages auto continue enum if short switch volatile C++ only keywords asm delete inline private static_cast try wchar_t

break default extern int signed typedef while bool dynamic_cast mutable protected template typeid

case do float long sizeof union

char double for register static unsigned

const else goto return struct void

catch explicit namespace public this typename

class false new reinterpret_cast throw using

const_cast friend operator true virtual

The Hashemite University


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:


The Hashemite University 31

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 Error cout<< Hello World\n; //Correct

The Hashemite University


Additional Notes

This lecture covers the following material from the textbook:

Fourth edition:

Chapter 1: Sections 1.20 and 1.21

The Hashemite University