cs1123 11 pointers

51
Introduction to C++ (CS1123) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad Fall 2013

Upload: talha-malik

Post on 22-Dec-2014

30 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Cs1123 11 pointers

Introduction to C++(CS1123)

By

Dr. Muhammad Aleem,

Department of Computer Science, Mohammad Ali Jinnah University, Islamabad

Fall 2013

Page 2: Cs1123 11 pointers

History

• C evolved from two languages (BCPL and B)

• 1980: “C with Classes”

• 1985: C++ 1.0

• 1995: Draft standard

• Developed by Bjarne Stroustrup at Bell Labs

• Based on C, added Object-Oriented Programming concepts (OOP) in C

• Similar program performance (compared to C)

Page 3: Cs1123 11 pointers

C vs C++• Advantages:

– 1. Faster development time (code reuse)

– 2. Creating / using new data types is easier

– 3. Easier memory management

– 4. Stricter syntax & type checking => less bugs

– 5. Easier to implement Data hiding

– 6. Object Oriented concepts

Page 4: Cs1123 11 pointers

C++ Program Structure//My first program in C++ First.cpp

#include <iostream>

using namespace std;

int main ()

{

cout << "Hello World!";

return 0;

}

Preprocessor Directive (no ;)

Page 5: Cs1123 11 pointers

IDE and Compilation Steps

C++ Preprocessor

First.cpp

C++ Compiler Linker First.exe

C++ Header Files

Object code for library function

Page 6: Cs1123 11 pointers

Integrated Development Environments (IDEs)

• An IDE is a software application which provides a comprehensive facility to programmers to Write /Edit

/Debug /Compile the code

• Main components:– Source code editor–Debugger–Complier–…

Page 7: Cs1123 11 pointers

IDEs on Windows platform

• Turbo C++

• Microsoft Visual C++

• Dev C++

Page 8: Cs1123 11 pointers

Input / Output Example#include <iostream>

#include <string>

using namespace std;

int main ( )

{

string name; //Name of student

cout<< “Enter you name";

cin>>name;

/* Now print hello , and students name */

cout<< “Hello “ << name;

return 0;

}

Page 9: Cs1123 11 pointers

Comments

• Two types of comments1. Single line comment //….2. Multi-line (paragraph) comment /* */

• When compiler sees // it ignores all text after this on same line

• When it sees /*, it scans for the text */ and ignores any text between /* and */

Page 10: Cs1123 11 pointers

Preprocessor Directives

• #include<iostream>

• # is a preprocessor directive.

• The preprocessor runs before the actual compiler and prepares your program for compilation.

• Lines starting with # are directives to preprocessor to perform certain tasks, e.g., “include” command instructs the preprocessor to add the iostream library in this program

Page 11: Cs1123 11 pointers

Header files (functionality declarations)(Turbo C++) (Visual C++)

• #include<iostream.h> or #include <iostream>• #include<stdlib.h> or #include<stdlib>• …

Page 12: Cs1123 11 pointers

std:: Prefix • std::cout<“Hello World”;• std::cout<<Marks;• std::cout<<“Hello ”<<name;• Scope Resolution Operator ::

• std is a namespace, Namespaces ?

using namespace std;cout<<“Hello World”;cout<<Marks;cout<<“Hello ”<<name;

Page 13: Cs1123 11 pointers

Namespaces

• Namespace pollution

–Occurs when building large systems from pieces

– Identical globally-visible names clash

– How many programs have a “print” function?

– Very difficult to fix

Page 14: Cs1123 11 pointers

Namespacesnamespace Mine {

const float pi = 3.1415925635; }

void main(){ float x = 6 + Mine::pi; cout<<x;}

Page 15: Cs1123 11 pointers

Multiple Namespaces

• Example…

Page 16: Cs1123 11 pointers

Omitting std:: prefix

- using directive brings namespaces or its sub-items into current scope

#include<iostream>using namespace std;

int main(){

cout<<“Hello World!”<<endl;cout<<“Bye!”;

return 0;}

Page 17: Cs1123 11 pointers

main( ) function• Every C++ program start executing from main ( )

• A function is a construct that contains/encapsulates statements in a block.

• Block starts from “{“ and ends with “}” brace

• Every statement in the block must end with a semicolon ( ; )

• Examples…

Page 18: Cs1123 11 pointers

cout and endl

• cout (console output) and the operator • << referred to as the stream insertion operator• << “Inserts values of data-items or string to screen.”• >> referred as stream extraction operator, extracts

value from stream and puts into “Variables”

• A string must be enclosed in quotation marks.

• endl stands for end line, sending ‘endl’ to the console outputs a new line

Page 19: Cs1123 11 pointers

Input and type– cin>>name; reads characters until a

whitespace character is seen

–Whitespace characters: • space, • tab, • newline {enter key}

Page 20: Cs1123 11 pointers

Variables - Variables are identifiers which represent

some unknown, or variable-value.

- A variable is named storage (some memory address’s contents)

x = a + b;Speed_Limit = 90;

Page 21: Cs1123 11 pointers

Variable declaration

TYPE <Variable Name> ;

Examples: int marks;double Pi;int suM;char grade;

- NOTE: Variable names are case sensitive in C++ ??

Page 22: Cs1123 11 pointers

Variable declaration• C++ is case sensitive–Example:

areaAreaAREAArEa

are all seen as different variables

Page 23: Cs1123 11 pointers

NamesValid Names• Start with a letter • Contains letters• Contains digits• Contains underscores

• Do not start names with underscores: _age

• Don’t use C++ Reserve Words

Page 24: Cs1123 11 pointers

C++ Reserve Words

• auto break• case char• const continue• default do• double else• enum extern• float for• goto if

int longregister returnshort signedsizeof staticstruct switchtypedef unionunsigned voidvolatile while

Page 25: Cs1123 11 pointers

Names• Choose meaningful names– Don’t use abbreviations and acronyms: mtbf, TLA,

myw, nbv

• Don't use overly long names• Ok:

partial_sumelement_countstaple_partition

• Too long (valid but not good practice):remaining_free_slots_in_the_symbol_table

Page 26: Cs1123 11 pointers

Which are Legal Identifiers? AREA 2D

Last Chance

x_yt3 Num-2

Grade***

area_under_the_curve _Marks #values areaoFCirCLe %done return Ifstatement

Page 27: Cs1123 11 pointers

String input (Variables)// Read first and second name

#include<iostream>

#include<string>

int main() {

string first;

string second;

cout << “Enter your first and second names:";

cin >> first >> second;

cout << "Hello “ << first << “ “ << second;

return 0;

}

Page 28: Cs1123 11 pointers

Declaring Variables

• Before using you must declare the variables

Page 29: Cs1123 11 pointers

Declaring Variables…• When we declare a variable, what happens ?–Memory allocation• How much memory (data type)

–Memory associated with a name (variable name)– The allocated space has a unique address

Marks

FE07

%$^%$%$*^%int Marks;

Page 30: Cs1123 11 pointers

Using Variables: Initialization• Variables may be given initial values, or

initialized, when declared. Examples:

int length = 7 ;

float diameter = 5.9 ;

char initial = ‘A’ ;

7

5.9

‘A’

length

diameter

initial

Page 31: Cs1123 11 pointers

• Are the two occurrences of “a” in this expression the same?

a = a + 1;One on the left of the assignment refers to the location

of the variable (whose name is a, or address);One on the right of the assignment refers to the value of

the variable (whose name is a);

• Two attributes of variables lvalue and rvalue • The lvalue of a variable is its address• The rvalue of a variable is its value

rvalue and lvalue

Page 32: Cs1123 11 pointers

• Rule: On the left side of an assignment there must be a lvalue or a variable (address of memory location)

int i, j;i = 7; 7 = i; j * 4 = 7;

rvalue and lvalue

Page 33: Cs1123 11 pointers

Data TypesThree basic PRE-DEFINED data types:

1. To store whole numbers

– int, long int, short int, unsigned int

2. To store real numbers

– float, double

3. Characters

– char

Page 34: Cs1123 11 pointers

Types and literals• Built-in types– Boolean type• bool

– Character types• char

– Integer types• int–and short and

long– Floating-point types• double–and float

• Standard-library types– string

Literals• Boolean: true, false

• Character literals– 'a', 'x', '4', '\n', '$'

• Integer literals– 0, 1, 123, -6,

• Floating point literals– 1.2, 13.345, 0.3, -0.54,

• String literals– "asdf”, “Helllo”, Pakistan”

Page 35: Cs1123 11 pointers

Types • C++ provides a set of types– E.g. bool, char, int, double called “built-in types”

• C++ programmers can define new types– Called “user-defined types”

• The C++ standard library provides a set of types– E.g. string, vector, .. – (for vector type #include<vector> )

Page 36: Cs1123 11 pointers

Declaration and initializationint a = 7;

int b = 9;

char c = 'a';

double x = 1.2;

string s1 = "Hello, world";

string s2 = "1.2";

7

9

a

1.2

Hello, world

1.2

Page 37: Cs1123 11 pointers

char type• Reserves 8 bits or 1 byte of memory • A char variable may represent:– ASCII character 'A‘, 'a‘, '1‘, '4‘, '*‘– signed integers 127 to -128 (Default)– unsigned integer in range 255 to 0

Examples:– char grade;–unsigned char WeekNumber= 200;– char cGradeA = 65; – char cGradeAA = ‘A';

Page 38: Cs1123 11 pointers

char type • Example program…

Page 39: Cs1123 11 pointers

Special characters• Text string special characters (Escape Sequences)– \n = newline – \r = carriage return – \t = tab– \" = double quote – \? = question– \\ = backslash – \' = single quote

• Examples:cout << "Hello\t" << "I\’m Bob\n";cout << "123\nabc “;

Page 40: Cs1123 11 pointers

Escape Sequence• Example Program:

Page 41: Cs1123 11 pointers

int type • 16 bits (2 bytes) on Windows 16-bits– int -32,768 to 32,767 – unsigned int 0 to 65,535– Also on Turbo C++, 2 bytes for int

• 32 bits (4 bytes) on Win32 (Visual C++)– int -2,147,483,648 to 2,147,483,647– unsigned int 0 to 4,294,967,295

Page 42: Cs1123 11 pointers

int type • Examples:

int earth_diameter;int seconds_in_week= 604800;unsigned int Height = 100;unsigned int Width = 50000;

Page 43: Cs1123 11 pointers

int type (long and short)• long int– reserves 32 bits (4 bytes) of memory – signed long -2,147,483,648 to 2,147,483,647–unsigned long int 0 to 4,294,967,295

• short int– reserves 16 bits (2 bytes) of memory – signed short int -32,768 to 32,767 –unsigned short int 0 to 65,535

Page 44: Cs1123 11 pointers

int (long and short)• Examples:

long int light_speed=186000;unsigned long int seconds= 604800;short int Height = 30432;unsigned short int Width = 50000;

Page 45: Cs1123 11 pointers

Home Work-1 • Use Visual C++ on Windows and get information

for following data types:– int– short– long int– short int– char

• Use ( cout << sizeof( intVar ); ) operator to get this information, Example:…

Page 46: Cs1123 11 pointers

Real Values• float– Reserves 32 bits (4 bytes) of memory

– + 1.180000x10+38

, 7-digit precision– Example: float radius= 33.4221;

• double– Reserves 64 bits (8 bytes) of memory

– + 1.79000000000000x10+308

, 15-digit precision– Example: double Distance = 257.5434342;

• long double– Reserves 80 bits (10 bytes) of memory , 18-digit precision– Example: long double EarthMass = 25343427.53434233;

Page 47: Cs1123 11 pointers

Home Work-2• Use Visual C++ on Windows and get information

for following data types:– float– double– long double

• Use ( cout << sizeof(floatVar); ) operator to get this information, Example:…

Page 48: Cs1123 11 pointers

bool Type• Only 1 bit of memory required– Generally, 1 byte because is reserved

• Literal values: – true– false

• Can be used in logical conditions:– Examples:

bool RainToday=false; bool passed; passed = GetResult(80);

Page 49: Cs1123 11 pointers

string type• Special data type supports working with “strings”

#include <string>

string <variable_name> = “string literal”;

• string type variables in programs: string firstName, lastName;

• Using with assignment operator:firstName = “Mohammad";lastName = “Ali";

• Display using coutcout << firstName << " " << lastName;

Page 50: Cs1123 11 pointers

Getting input in string with Spaces

string s1;cin>> s1; //Spaces will not be input in s1

//Following statements read spaces in “string”string s1;getline(cin, s1); //Spaces will be input in s1

Page 51: Cs1123 11 pointers

string type • Find Errors in the example program…