part 1 basics c++

Upload: lalitha

Post on 29-May-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Part 1 Basics c++

    1/34

    C++ PROGRAMMING SKILLS

    Part 1

    Basics of C++

    C++ Overview

    Elements I / O

    Assignment and Comments

    Formatted Output

  • 8/9/2019 Part 1 Basics c++

    2/34

    History ofC and C++

    BCPL 1967By Martin RichardsLang. to write OS

    NO Data Type

    B :By Ken ThompsonUsed to create early UNIX

    @ Bell lab's 1970NO Data Type

    C :By Dennis Ritchie @ Bell labs-UNIX written in C-HW Independent

    -many versions in late 1970s

    OO Features

    C++: ByBjarne Stroustrap

    Early1980s @ Bell labsProvides OO programming

    Standard ANSI C

    In 1980 was approved

    Java: In 1995 bySun Microsystems

    OO Features

    +

    +

    +

    +

  • 8/9/2019 Part 1 Basics c++

    3/34

    Arithmetic

    Arithmetic calculations Use * for multiplication and / for division

    Integer division truncates remainder

    7 / 5 evaluates to 1

    Modulus operator returns the remainder

    7 % 5 evaluates to 2

    Operator precedence

    Some arithmetic operators act before others (i.e.,multiplication before addition)

    Be sure to use parenthesis when needed

    Example: Find the average of three variables a, b and c

    Do not use: a + b + c / 3

    Use: (a + b + c ) / 3

  • 8/9/2019 Part 1 Basics c++

    4/34

  • 8/9/2019 Part 1 Basics c++

    5/34

    Equality and Relational Operators

    Sta nda rd a lge bra icequality op erato r orrela tiona l operator

    C++ eq ua lityor relationa loperator

    Exampleo f C++condition

    Mea ning o fC++ cond ition

    Relational operators

    > > x> y x is r at r t an y

    < < x < y x is less t an y

    u >= x>= y x is reater t an or equal to y

    e

  • 8/9/2019 Part 1 Basics c++

    6/34

    Logical Operators

    Truth TableMeaningOperator in C++

    OUTPUTINPUT

    Exp1 Exp2

    F

    FF

    T

    F F

    F TT F

    T T

    Logical AND&&

    F

    T

    T

    T

    F F

    F T

    T F

    T T

    Logical OR

    ||

    T

    F

    F

    T

    Logical NOT!

  • 8/9/2019 Part 1 Basics c++

    7/34

    Operators Precedence update

    Operator(s) Operation(s) Order of evaluation (precedence)

    () Parentheses Evaluated first. If the parentheses are nested, the expression

    in the innermost pair is evaluated first. If there are severalpairs of parentheses on the same level (i.e., not nested),they are evaluated left to right.

    , +, - Logical NOT, signs Evaluated second. If there are several, they reevaluated right to left.

    *, /, or% Multiplication DivisionModulus

    Evaluated third. If there are several, they reevaluated left to right.

    +or- AdditionSubtraction

    Evaluated fourth. If there are several, they areevaluated left to right.

    >, =,

  • 8/9/2019 Part 1 Basics c++

    8/34

    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 replacesthe previous value - it is destroyed

    Reading variables from memory does not change them

    A visual representation

    integer1 45

  • 8/9/2019 Part 1 Basics c++

    9/34

    Variable Names (Identifiers)

    Letter + {Letters and/or Digits and/or ( _ )

    _ +Letter+{Letters and/or Digits and/or ( _ )

    CorrectionExplanation ?Invalidforty_Hours , hours40Begin with a digit40Hours

    get_Date , getDateBlanks not allowedGet Date

    box_22 , box22The hyphen(-) is minusBox-22

    costInUSDollarSpecial symbols notallowed

    cost_in_$

    int_1Reserved word in C++int

    Underscore character ( _ )

    Naming Convention(Style)

    Variables LengthInYard , hours

    FunctionsCalcAverage , Cube(27)

    ConstantMAX_HOUR , LIMIT

  • 8/9/2019 Part 1 Basics c++

    10/34

    Data Types short int :Range of values ( 32,767 ).

    long int :Range of values ( 2,147,483,647 ).

    int : Integer numbers float: floating point used for working with real numbers.

    double: is a floating point type much like float , but it can store a value ofmuch greater magnitude with greater precision.

    Bool*: is a boolean data type can take two value TRUE or FALSE.

    *Note:- bool data type is provided by ANSI/ISO C++ standard. It is undefined in Borland Turbo C++.

    char : character data type (alpha,digit,special-symbol or space).

    A single character with its value quoted with single-quotation

    egs. A , a , $ , , 8

    string: for working with multiple characters including letters, numbers ,special symbols and spaces its value quoted with double- quotation.

    egs. C++ , Computer Science , .

    Letter S.Symbol Space Digit

  • 8/9/2019 Part 1 Basics c++

    11/34

    Declaration of Variables

    Data Type Identifier1, Identifier2,;

    Examples and preference:

    charLetter, middleInt , ch;

    charLetter;charmiddleInt;charch;

    Constant Variables

    constData Type Identifier=value;

    Examples:

    conststringSTARS=*****;constcharch=$;const floatMAX_Hour=40.0

  • 8/9/2019 Part 1 Basics c++

    12/34

    Assignment Statement

    Store the value of the Expression into the variable, any previous value of the variableis destroyed.

    Example:Giving the declarations

    string firstname;

    charletter;int num;

    Remark :Double or more assignment allowed and precedence from Right-to-Left

    eg. N1=n2=n3=5;

    Variable = Expression ;

    firstname=Sara;num = 5;num=5*5-3;letter=S

    Valid Assignment

    firstname=Sara;firstname=;

    letter=S

    Invalid Assignment

  • 8/9/2019 Part 1 Basics c++

    13/34

    Output statement

    Example: Given ch=2 and firstname=Ali

    and lastname=Ahmad

    cout

  • 8/9/2019 Part 1 Basics c++

    14/34

    Comments

    C++ Preprocessor

    #include :- This line known as Preprocessor Directive its nothandled by C++ compiler but by a program known as Preprocessor.

    iostream :- Headerfile contains declarations of I/O facilities.

    Preprocessor program acts as a filter before compilation.

    /* ..Text... Text */

    // Text

    For Multiple Lines

    For Single Line

    The compiler ignores comments (Not executable)

    Source program PreprocessorExpanded Source

    programC++ Compiler

  • 8/9/2019 Part 1 Basics c++

    15/34

    Input statement

    cin >> variable1 >> variable2 ;

    It needs #include preprocessor directive that contain istream cinostream cout.

    cin>>Length>>width;cin>>Length;cin>>width;

    Example:-

    The Same

    cin>>i>>ch>>x; 25 A 16.9

    1:-

    2:-

    i=25 ch=A x=16.9

    Statement Data Contents after input

    3:- cin>>i>>j>>x; 12 8 i=12 j=8 (computer wait for the third number)

    cin>>i>>x; 46 32.4 15 i=46j=32.4 (15 is held for later input)4:-

    New line character \n is considered one charactereg. cout

  • 8/9/2019 Part 1 Basics c++

    16/34

    Input statement(cont.)

    Note :- cant input SPACE character , the >> skips white space(blank) character.

    cin.get() FUNCTION READS ONE CHARACTER FROM THEKEYBOARD (Does not skips space characters)

    eg.

    ch1=cin.get() R cin>>ch1

    ch2= cin.get() ch2=cin.get()

    ch3=cin.get() 1 cin>>ch3

    Given input: R 1

  • 8/9/2019 Part 1 Basics c++

    17/34

    Operators Precedence update

    Operator(s) Operation(s) Order of evaluation (precedence)

    () Parentheses Evaluated first. If the parentheses are nested, the expression in the

    innermost pair is evaluated first. If there are several pairs of

    parentheses on the same level (i.e., not nested), they are evaluated

    left to right.

    !, +, - Logical NOT, signs Evaluated second. If there are several, they are evaluated right to left.

    *, /, or% Multiplication Division

    Modulus

    Evaluated third. If there are several, they are evaluated left to right.

    +or- Addition

    Subtraction

    Evaluated fourth. If there are several, they are evaluated left to right.

    >>, , =,

  • 8/9/2019 Part 1 Basics c++

    18/34

    C++ program development goes through six steps: Step1: Edit (using text editor to type, correct and save the program

    file).

    Step2: preprocessor, automatically before compile, executes toinclude other text files in the file to be compiled.

    Step3: Compile , the compiler translates the C++ code intomachine language (also called object-code).

    Step4: Link , it is linking any used functions that are definedelsewhere such as standard libraryfunctions, or private libraryfor agroup ofprogrammers, linker, links the object code with the code for

    the missing functions to provide full code Step5: Load, a program before executing , must be loaded into the

    main memory, loader does this task , loading code from disk.

    Step6: Execute, the computer under the control of its CPUexecutes the program. Instruction by instruction.

    Phases of C++ Programs

  • 8/9/2019 Part 1 Basics c++

    19/34

    Phases o C++ Pro ra s:

    1 dit

    2 Preprocess

    3 Co pile

    4. Link

    5. Load6. Execute

    Loader

    main

    Memory

    Program is created

    inthe editor and storedon disk.

    Preprocessorprogramprocesses the code.

    Loader puts programin memory.

    CPU takes each

    instruction andexecutes it, possiblystoring new datavalues as the

    programexecutes.

    CompilerCompiler createsobject code andstores

    it on disk.

    Linker links the objectcode with the libraries,creates a.out and

    stores it on disk

    Editor

    Preprocessor

    Linker

    CPU

    main

    Memory

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    .

    Disk

    Disk

    Disk

    Disk

    Disk

    illustration of C++ Program Phases

  • 8/9/2019 Part 1 Basics c++

    20/34

    Structure of C++ program

    Ever y C++ program must have a function named main. The programmer can choose to

    decompose the program into several parts (user-defined functions). Think ofmain as themaster and the otherfunctions are the servants.

    The execution always starts with main.

    #include

    int main( ){ Declarations ;

    Executable Statement_1 ;

    Executable Statement_2 ;

    :

    Executable Statement_n ;

    return 0;}

    Preprocessor Directive

    Type of returned value

    Marks the start of themain function (program)

    Marks the end of themain function (program)

    Headerfile facilitateI/O

    Returning 0 meansevery things is OKelse(1,2,..) somethingwent wrong (Exit Status)

  • 8/9/2019 Part 1 Basics c++

    21/34

    C++ Programming Examples

    C++ language

    Facilitates a structured and disciplinedapproach to computer program design

    Following are several examples The examples illustrate many important

    features of C++

    Each example is analyzed one statement at atime.

  • 8/9/2019 Part 1 Basics c++

    22/34

    1. Comments

    2. Load

    3.main

    3.1 Print "Welcometo C++\n"

    3.2 exit (return 0)

    1 // Fig.1.2:fig01_02.cpp

    2 // Afirstprogramin C++

    3 #include

    4

    5 intmain()

    6 {

    7 cout

  • 8/9/2019 Part 1 Basics c++

    23/34

    A Simple Program: Printing a Line of Text

    cout Standard output stream object

    Connected to the screen

  • 8/9/2019 Part 1 Basics c++

    24/34

    A Simple Program: Printing a Line of Text

    There are multiple ways to print text Following are more examples

    Escape equence escripti n

    \n Newline. P siti n thescreencursor to the

    beginningofthenext line.

    \t Horizontal tab. ove thescreencursor to thenexttab stop.

    \r Carriagereturn. Position thescreencursor to the

    beginningofthecurrent line; onot advance to thenext line.

    \a Alert. ound thesystem bell.

    \\ Backslash. Used toprint a backslash character.

    \" oublequote. Used toprint adoublequotecharacter.

  • 8/9/2019 Part 1 Basics c++

    25/34

    1. Load

    2.main

    2.1 Print "Welcome"

    2.2 Print "to C++!"

    2.3 newline

    2.4 exit (return 0)

    Program OutputWelcometo C++!

    1 // Fig.1.4:fig01_04.cpp

    2 // Printingaline with multiple statements

    3 #include

    4

    5 intmain()

    6 {

    7 cout

  • 8/9/2019 Part 1 Basics c++

    26/34

    1. Load

    2.main

    2.1 Print "Welcome"

    2.2 newline

    2.3 Print "to"

    2.4 newline

    2.5 newline

    2.6 Print "C++!"

    2.7 newline

    2.8 exit (return 0)

    Program Output

    1 // Fig.1.5:fig01_05.cpp

    2 // Printing multiplelines witha single statement

    3 #include

    4

    5 intmain()

    6 {

    7 cout

  • 8/9/2019 Part 1 Basics c++

    27/34

    Another Program: Adding Two Integers

    >> (stream extraction operator) When used with cin, waits for the user to input a value andstores the value in the variable to the right of the operator

    The user types a value, then presses the Enter (Return) key tosend the data to the computer

    Example:int myVariable;

    cin>> myVariable;

    Waits for user input, then stores input inmyVariable

    = (assignment operator) Assigns value to a variable

    Binary operator (has two operands) Example:

    sum= variable1 + variable2;

  • 8/9/2019 Part 1 Basics c++

    28/34

    1. Load

    2. main

    2.1 Initialize variables

    integer1, integer2,and sum

    2.2 Print "Enter firstinteger"

    2.2.1 Get input

    2.3 Print "Entersecond integer"

    2.3.1 Get input

    2.4 Add variables and putresult into sum

    2.5 Print "Sum is"

    2.5.1 Output sum

    2.6 exit (return 0)

    Program Output

    1 // Fig.1.6:fig01_06.cpp

    2 // Additionprogram

    3 #include

    4

    5 intmain()

    6 {7 int integer1,integer2, sum; // declaration

    8

    9 cout >integer1; //readaninteger

    11 cout >integer2; //readaninteger

    13 sum=integer1 + integer2; //assignment of sum

    14 cout

  • 8/9/2019 Part 1 Basics c++

    29/34

    Built-in (Library) Function

    Function Exponentiation

    pow (x, y) x is raised to powery; (xy )sqrt (x) Square-root ofxsin (x) Sine of x cos (x) Cosine ofx tan (x) Tangent of x exp (x) Exponentiation ofx, ( ex)fabs (x) Absolute Value ofx, | x |log (x) Logarithm ofx (base e)log10 (x) Logarithm ofx (base 10)floor (x) Rounding-down xceil (x) Rounding-up x

    ______etc. {there are more}_______________________Eg.1. floor (9.2) = 9.0Eg.2. floor (-9.8) = -10.0 Remark:you need to include to be able to use these

    functions. In newer versions it is #include

  • 8/9/2019 Part 1 Basics c++

    30/34

    Good Programming practices

    Keep it simple do not stretch the language.

    Read C++ manual.

    Experiment a feature by writing a simple program and test it.

    Start your program with a comment to indicate what the programdoes?

    Use new line \n to make output more organized. Indent the body of each function one level, more indents for nesting.

    Choose meaningful variables, constants and function names.

    Use spaces after commas, operators and new lines betweendeclaration and executable statement.

    One statement per line.Note: The function time(0) returns the current calendar time in seconds

    calculated from 1970.

    It needs: #include // turbo C++

    #include // Visual C++

  • 8/9/2019 Part 1 Basics c++

    31/34

    Common programming Errors

    Divide by zero. Not including iostream for input/output operations.

    Forgetting the (;) at end of each statement.

    Using % with non-integer.

    Ifa space found between the pair-of-symbols for therelational operators. (i.e., > = instead of >= ).

    Confusing the equality == with the assignment =.

    Reversing the order of the relational operators

    (i.e., => isntead of >=).

  • 8/9/2019 Part 1 Basics c++

    32/34

    Formatted Output

    setwcan be used to specify the width o

    fthe

    field that the next value o

    foutputwill be printed in. To use it, you must include headerfile.

    eg1:-

    int num=12;

    cout

  • 8/9/2019 Part 1 Basics c++

    33/34

    Formatted Output(cont1)precision and setprecision for printing formatted floating point values

    You may set the Number of

    Digits that appear on the right of

    the decimal-point the wayyou like it to be.

    it can be done by either setprecision stream manipulator, or precision memberfunction.

    eg. Using both to output the square root of 2

    #include#include

    #includeint main( ){double root2=sqrt(2.0);int places;cout

  • 8/9/2019 Part 1 Basics c++

    34/34

    11.41.411.4141.41421.414211.414214

    1.41421361.414213561.414213562

    Output

    1

    1.41.41

    1.4141.41421.414211.4142141.41421361.414213561.414213562

    Square root of 2 with precision 0-9 usingprecision memberfunction

    Using setprecision manipulator

    Formatted Output(cont2)