01-Basic of C++

download 01-Basic of C++

of 59

Transcript of 01-Basic of C++

  • 7/31/2019 01-Basic of C++

    1/59

    Basic of C++

  • 7/31/2019 01-Basic of C++

    2/59

    Lecture Overview

    Introduction to C++ Basic components of C++

    Control Statements

    Declarations

    Functions

    Useful Library in C

    2

  • 7/31/2019 01-Basic of C++

    3/59

    What is C++?

    A programming language developed by BjarneStroustrup

    Originally known as C with Classes

    Renamed to C++ in 1983

    First commercial release in 1985 Main features:

    General purpose

    Object Oriented

    Compatibility with C

    3

    http://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.html
  • 7/31/2019 01-Basic of C++

    4/59

    The Good and Bad News

    Good News:

    Only minor incompatibility with C

    Most programs in C are valid in C++ withoutmodification

    Proficiency in C++ is a great advantage: Much sought after in the industry

    Picking up other OO languages like Java, C# isrelatively easy

    Bad News: Compatibility with C detracts from pure Object

    Oriented approach

    4

  • 7/31/2019 01-Basic of C++

    5/59

    Advice

    C++ is only a means used in learning datastructures and algorithms C++ coverage is done within 3-4 lectures!

    Focus more on concepts and Ideas that are trueregardless of the actual implementation language

    However, a heavy weight of your CA comes fromyour C++ proficiency: Labs

    Programming questions in the midterm test and the final

    exam

    5

  • 7/31/2019 01-Basic of C++

    6/59

  • 7/31/2019 01-Basic of C++

    7/59

  • 7/31/2019 01-Basic of C++

    8/59

    Hello World! in C and C++

    #include

    using namespace std;

    int main () {

    cout

  • 7/31/2019 01-Basic of C++

    9/59

    Another simple C++ program#include

    using namespace std;

    const double PI = 3.14159;

    int main () {

    int radius;

    cout > radius;

    double area = PI * radius * radius;

    double circumference = 2 * PI * radius;cout

  • 7/31/2019 01-Basic of C++

    10/59

  • 7/31/2019 01-Basic of C++

    11/59

    Control Statements

    Program Execution Flow

  • 7/31/2019 01-Basic of C++

    12/59

    Selection Statements - 1 if-else statement

    Valid comparison: boolean expression

    Primitive values (0 = false, nonzero = true)

    if (a > b) {

    ...

    } else {

    ...

    }

    12

    // L01p3.cpp

    #include using namespace std;int main () {

    int i = -1;double d = 2.0;if ( d > i ) cout

  • 7/31/2019 01-Basic of C++

    13/59

  • 7/31/2019 01-Basic of C++

    14/59

  • 7/31/2019 01-Basic of C++

    15/59

  • 7/31/2019 01-Basic of C++

    16/59

    Simple Data Types

    Integer data

    Unsigned version can store only non-negative values

    Character data

    Unsigned version can store only non-

    negative values

    Floating point data

    int

    unsignedint

    Constant modifier

    As prefix of data types

    E.g. const int i = 123;

    Variable must be initialized when declaredand cannot be changed afterwards

    const

    16

    char

    unsignedchar

    float

    double

    [new]

  • 7/31/2019 01-Basic of C++

    17/59

    Simple Data Types [new]

    Boolean data

    Can have the value true or false only

    Internally, true = 1, false = 0

    Can be used in a condition

    Improve readability

    bool

    bool done = false;

    while (!done) {

    if (...)

    done = true;

    }

    Condition met, Im done

    While not done

    Example Usage

    17

    // L01p5.cpp#include using namespace std;int main () {

    bool done = false;int i = 1;while (!done) {

    cout

  • 7/31/2019 01-Basic of C++

    18/59

  • 7/31/2019 01-Basic of C++

    19/59

    Enumeration [new]Color myColor;

    ...

    switch (myColor) {case Red:

    ...

    case Yellow:

    ...

    case Green:

    ...}

    int myInt;

    myInt = myColor;

    Color newColor;

    newColor = Color(1);

    enumcan be used in a switchstatement

    enumcan be converted to integerBy default, 1st value == 0, 2nd value == 1 etc.i.e. Red = 0, Yellow = 1,

    Similarly, integer can be converted toenumtype

    newColor will have the value Yellowin this case

    19Can you define bool as an enumeration?

  • 7/31/2019 01-Basic of C++

    20/59

    ArrayAn array is a collection of homogeneous data (data of

    the same type)To declare an array of 10 integers:

    int iA[10];

    20

    // L01p6.cpp

    #include using namespace std;int main () {

    int iA[10];iA[0] = 123;iA[9] = 456;

    iA[11] = iA[0] + iA[9];cout

  • 7/31/2019 01-Basic of C++

    21/59

    sizeof( )

    Use sizeof( ) to find the number of bytes taken by a

    variable (data type).

    21

    // L01p7.cpp#include using namespace std;enum Color {

    Red, Yellow, Green};int main () {

    int iA[] = {3,1,5,6,9,3,5,7,3,8,9,4,5,3,2,8,0};cout

  • 7/31/2019 01-Basic of C++

    22/59

    How are variables allocated?

    // L01p8.cpp

    #include using namespace std;

    int main () {

    int i,j;

    char a,b,c,d;

    int m;

    char e;

    int n;

    cout

  • 7/31/2019 01-Basic of C++

    23/59

    Array

    Limitation:

    A function return type cannot be an array

    An array parameter is passed by address

    An array cannot be the target of an assignment

    int[10] someFunction( ) {...}

    int ia[10], ib[10];// Initialize array ib

    ia = ib;

    Error: cannot return array

    Error: array assignment isinvalid

    23

  • 7/31/2019 01-Basic of C++

    24/59

    Structure A collection of heterogeneous data

    Data can be of different type Data describe a common entity

    Declaring the structure called

    Person to store informationabout a person:

    name: maximum 50 characters

    age: integer

    gender: m = male; f = female

    s1 is a Person variable

    struct Person {

    char name[50];int age;

    char gender;

    };

    Person s1;

    24

  • 7/31/2019 01-Basic of C++

    25/59

    Structure Example Usage

    Person s1 = { Potter, 13, m };

    Person s2;

    s2 = s1;

    s1.age = 14;

    s2.gender = f;

    s2.age = s1.age * 2;

    Declare & Initialize

    Structure assignment. Everything copied.

    Use . to access a field

    Declare only

    Read and store a field

    25

  • 7/31/2019 01-Basic of C++

    26/59

    Size of a structure// L01p9.cpp

    #include

    using namespace std;

    struct Person {

    char name[50];

    int age;

    char gender;};

    int main () {

    Person s1 = { "Potter", 13, 'm' };

    Person s2;

    cout

  • 7/31/2019 01-Basic of C++

    27/59

    Pointer

    A pointer contains the addressof a memory location

    111

    1024

    1024

    x

    addressname content

    ptr

    int x = 111;

    int *ptr;

    ptr = &x;

    *ptr = 123;

    Declareptr as an int pointer

    ptr points to x

    Dereferenceptr

    Note the different meanings of *

    Declaring a pointer

    Deference a pointer

    27

    123

  • 7/31/2019 01-Basic of C++

    28/59

  • 7/31/2019 01-Basic of C++

    29/59

  • 7/31/2019 01-Basic of C++

    30/59

  • 7/31/2019 01-Basic of C++

    31/59

  • 7/31/2019 01-Basic of C++

    32/59

    {

  • 7/31/2019 01-Basic of C++

    33/59

    Pointer and Structure

    Pointer can point to a structure

    int main()

    {

    Person s =

    { "Potter", 13, 'm' };

    Person *p; //Person Pointer

    p = &s;

    p->age = 14;

    (*p).age = 14;

    }

    EquivalentStatements

    'P'

    13

    1024

    1074

    'm ' 1078

    1024

    sage

    name

    gender

    p

    33

    struct Person {

    char name[50];

    int age;

    char gender;

    };

    Person s1;

    14

  • 7/31/2019 01-Basic of C++

    34/59

    Dynamic Memory Allocation : new [new]

    Up to now, pointers are used to point to existing

    (declared) variable Actually, new memory box can be allocated at runtime

    Using the new keyword

    Syntax:

    new datatypewhere datatypecan be

    Predefined data type: int, float, array

    User defined data type: structure or class

    Address of the start of the newly allocated memoryboxes is then returned

    Usually we use a pointer variable to store the address

    34

  • 7/31/2019 01-Basic of C++

    35/59

  • 7/31/2019 01-Basic of C++

    36/59

  • 7/31/2019 01-Basic of C++

    37/59

    new : Array of elements

    Whole array can be allocated dynamically The size can be supplied at run time

    intmain()

    {

    int size;

    int *ia;

    cout > size;

    ia = new int[size];

    ia[0] = ...

    ia[1] = ...

    }

    ia

    Assume size = 5

    37

  • 7/31/2019 01-Basic of C++

    38/59

  • 7/31/2019 01-Basic of C++

    39/59

  • 7/31/2019 01-Basic of C++

    40/59

    delete : An example/* PERSON: a structure definedbefore*/

    intmain(){

    Person *p;

    p = new Person;

    p->age = 14;

    delete p;

    p = NULL;

    p->age = 14;

    }

    p

    Good Practice: Always set a

    pointer to NULL after delete

    Error!

    Freememory

    40

    NULL

  • 7/31/2019 01-Basic of C++

    41/59

    General Advices on using Pointers

    Incorrect / Careless use of pointers can make your

    life miserable: Program Crashes (Runtime Error):

    Segmentation Fault / Bus Error

    "Weird" behavior:

    Program works erratically

    Useful Guidelines: Always initialize a pointer

    Set to NULL When:

    Declaring a new pointer

    After memory deallocation

    Make sure a pointer is pointing to the right place!

    41

  • 7/31/2019 01-Basic of C++

    42/59

    Reference [new]

    A reference is an alias

    (alternative name) for a variable

    x

    name content

    intRef 456

    int x = 456;

    int& intRef = x;

    // type of intRef is intintRef++;

    cout

  • 7/31/2019 01-Basic of C++

    43/59

  • 7/31/2019 01-Basic of C++

    44/59

    Function

    Modular Programming

  • 7/31/2019 01-Basic of C++

    45/59

    Function A function is a group of statements within a named block marked by { }

    SyntaxReturn-type function-name(parameters) {

    // body

    }

    only relies on parameters for input

    output is well defined When the block is replaced by ;, we have the corresponding function

    prototype

    int factorial(int n)

    {

    int result = 1, i;for (i = 2; i

  • 7/31/2019 01-Basic of C++

    46/59

    Function Prototype and Implementation

    int factorial( int );

    int main( )

    {

    cout

  • 7/31/2019 01-Basic of C++

    47/59

  • 7/31/2019 01-Basic of C++

    48/59

    Function Overloading [new]int maximum(int a, int b) //Ver.1

    {

    if (a > b) return a;

    else return b;

    }

    int maximum (int a, int b, int c) //Ver.2

    {return max( max(a, b), c);

    }

    float maximum(float a, float b) //Ver.3

    {if (a > b) return a;

    else return b;

    }

    3 versions ofmaximum() function.

    Note the difference in number and data type of parameters

    48

  • 7/31/2019 01-Basic of C++

    49/59

    Function Overloading [new]

    Whenever an overloaded function is called, the

    compiler chooses the closest match1. Exact match

    2. Safe promotion, e.g. char int, float double

    3. Unsafe conversion, e.g. double float

    maximum(1, 2, 3);

    maximum(a, b);

    double f1, f2;

    maximum(f1, f2);

    Version 2 called

    Version 1 called

    Version 3 called

    49

  • 7/31/2019 01-Basic of C++

    50/59

    f A

  • 7/31/2019 01-Basic of C++

    51/59

    Function : Default Argument [new]

    In C++, function parameter can be given a default value

    Default value is used if the caller does not supply anactual argument

    double logarithm( double N, double base = 10 )

    { ... Calculates Logbase(N) ... }

    int main( )

    {

    cout

  • 7/31/2019 01-Basic of C++

    52/59

    Function : Default Argument [new]

    Parameters with default values should appear last in

    the parameter list E.g. f(int i, int j = 123, int k = 456)

    But not f(int i, int j = 123, int k)

    Similarly, when using a function with defaultparameters

    Only trailing arguments can be omitted

    E.g. Given

    f(int i, int j = 123, int k = 456)

    f(999); //ok. Equal to f(999, 123, 456)

    f(999, 888); //ok. Equal to f(999, 888, 456)

    f(999, , 777); //compilation error

    52

  • 7/31/2019 01-Basic of C++

    53/59

  • 7/31/2019 01-Basic of C++

    54/59

    F i P b dd / i

  • 7/31/2019 01-Basic of C++

    55/59

    Function : Pass by address/pointer

    void swap_ByAdr( int* a, int* b )

    { int temp;

    temp = *a;

    *a = *b;

    *b = temp;

    }

    123

    456

    1024

    1028

    1024

    1028

    i

    j

    a

    b

    55

    int main()

    { int i = 123, j = 456;

    swap_ByAdr(&i, &j);

    cout

  • 7/31/2019 01-Basic of C++

    56/59

    F i A P i S

  • 7/31/2019 01-Basic of C++

    57/59

    Function : Argument Passing Summary

    By Value: Simple data types (int, float, char etc) and simple

    structures are passed by value (copying the arguments)

    Cannot change the actual argument

    By Address:

    Requires the caller to pass in the addresses of variablesusing &

    Requires dereferencing of parameters in the function

    Arrays are passed by address

    By Reference: No additional syntax required except to declare the

    parameters as reference variables

    No copying of arguments

    Faster execution and less memory usage

    57

  • 7/31/2019 01-Basic of C++

    58/59

    Useful Library

    Cant live without them

  • 7/31/2019 01-Basic of C++

    59/59