C++Lect1

Embed Size (px)

Citation preview

  • 8/12/2019 C++Lect1

    1/16

  • 8/12/2019 C++Lect1

    2/16

    C++ Lecture 1 OOP

    Example:/ / Wr i t e a pr ogr am whi ch reads 2 i nt egers a and b f r om t he keyboar d/ / Cal cul at e ( a+b) *( a+b) and ( a- b) *( a- b)

    #i ncl ude #i ncl ude

    i nt a, b; / / a, b ar e gl obal var i abl es

    voi d dat aI nput ( ) ; / / f unct i on decl ar at i on

    voi d mai n ( voi d) / / mai n f unct i on{ cl r s cr ( ) ;

    pr i nt f ( "t he pr ogr am r eads 2 i nt eger numbers and comput e. . . \ n") ;dat aI nput ( ) ;pr i nt f ( "\ n( a+b) *( a+b) =%6d", ( a+b) *( a+b) ) ;pr i nt f ( " \ n( a- b) *( a- b) =%6d", ( a- b) *( a- b) ) ;get ch( ) ;

    }

    voi d dat aI nput ( ) / / f unct i on i mpl ement at i on{ pr i nt f ( "\ nt he f i r st number =") ;

    scanf ( "%d", &a);pr i nt f ( " \ nt he second number (

  • 8/12/2019 C++Lect1

    3/16

    C++ Lecture 1 OOP

    Examples:#i ncl ude ; / / St an d ard I nput Out put Header#i ncl ude ; / / I nput & O t put eamu St r#i ncl ude ; / / Consol e In put Out put ( Crt )

    Symbolic constants are defined by define directive:

    #def i ne const ant Name characters string // without = Example:

    #def i ne PI 3. 141592 / / 3. 141592 r epl ace ever y PI appear ance

    A symbolic constant can be redefined or cancelled by the undef directive:

    #undef const ant Name

    1.3. About functions

    Every function is formed by a header ( function heading ) and a function body .Every function can be called if it was defined or declared.The general form for a function heading is:

    (list of formal parameters)

    where: < return type > indicates what type of value will be returned to the caller, if

    expected, otherwise is void type; < function name > is any valid identifier (should be descriptive); the list of formal parameters consists of a series of pairs of names, the first

    name is the name of a data type, and the second name is the name of a formal parameter; the pairs in the list must be separated by commas.

    Example: i nt MI NI MUM ( i nt a, i nt b) / / f uncti on headi ng{ i f ( a< execut abl e st at ement s >

    }

    Examples: i nt GCD( i nt a, i nt b) / / Greatest Common Di vi s or ( a , b)

    { i f ( b= =0) r etur n a;el se r et ur n GCD ( b, a % b) ; / / GCD( b, a modul o b ) ;}

    i nt GCD( i nt a, i nt b) / / Greatest Common Di vi s or ( a , b){ i nt r es t ;

    do { r est =a%b; / / r est a / ba=b;b=r est ;

    }whi l e ( rest !=0) ; / / r e st 0; or whi l e ( r e s t ) ;r et ur n a;

    }

    23.03.06 3

  • 8/12/2019 C++Lect1

    4/16

    C++ Lecture 1 OOP

    1.4. Language components

    C Alphabet consists by capital letters and small letters, decimal digits andspecials characters (like \n=CrLf, or \t=Tab).

    Every identifier name contains letters (plus _) and digits (first character must bea letter). Some identifiers are keywords, which are non-free context (examples: case ,

    float , int , long, return, short, static, structure, switch, union, unsigned, void ).

    The predefined types are the following:

    int (Z [-2 15,215-1]), short (Z [-2 15,215-1]), long (Z [-2 31,231-1]), unsigned (N [0,2 16-1]),

    float (Q * [-3.4 10 -38 , 3.4 1038]), double (Q * [-1.7 10 -308 , 1.7 10308]), char (cod ASCII) .

    Numerical Constants can be decimals (123, 123 L ong , 111 long), octal (077), hexadecimal(0xabba, 0XBABA ), or floating (2.71828, 6.023 e23, 6.023 E23).

    Character constants are printable ('A', '0', ' "'); functional ('\b'= Backspace , '\r'= Return ,'\n'= Newline , '\ ''= Apostrophe , '\ \'= Backslash , '\v'= Vertical tab , '\f'=page break, '\0'= Null .

    Character string constant consist by a text border by quotas ("Message").

    Simple variables declaration :

    ;

    Example: i nt i , j ; f l oat x, y; char c;

    Array declaration :

    arrayName [d 1] [d 2] ... [ d i] ... [ d n]; // index k i: 0 k i

  • 8/12/2019 C++Lect1

    5/16

    C++ Lecture 1 OOP

    Example:

    VExterne.Cpp :#i ncl ude ;#i ncl ude " Fs.h " ;f l oat Pi =3. 14; / / gl obal var i abl evoi d mai n ( voi d){ f l oat r ;

    pr i nt f ( "Ent er t he c i rc l e r adi us : " ) ;scanf ( "%f ", &r ) ;pr i nt f ( " c i rc l e wi dt h = %f \ n" , c i r c l eWi dt h( r ) ) ;scanf ( " \ n" ) ;

    }

    Fs.h :f l oat ci r c l eWi dt h ( f l oat r ){ extern f l oat Pi ; / / ext er n var i abl e

    r etur n 2* Pi * r ;}

    1.6. Local variablesA local variable used (is visible) only in the module or function in which it was

    defined. It can be dynamically allocated ( automatic variable , allocated in HEAP) orstatically allocated ( static variable , allocated in memory area of the program). A localvariable is implicitly automatic, and if we wish to be static, its declarations must have thefollowing form, using the static keyword:

    static < variableDeclara ion >

    The functions have implicitly the extern attribute, which means that they can be

    called from other source files. If we decide not to allow their call from other source files,we must declare them as static by writing the static keyword before its heading:st at i c f unct i onHeadi ng

    Example:

    VLocale.Cpp :#i ncl ude #i ncl ude "Sur sa. h"voi d mai n ( voi d){ i nt n;

    pr i nt f ( "Ent er a number < 256 : ") ; scanf ( "%d", &n) ;pr i nt f ( "Hexadeci mal val ue i s ") ;pr i nt Hexa( n) ;scanf ( " \ n" ) ;

    }

    Sursa.h :st exaDi gi t ( i nt s )atic i nt h

    { static int c;i f ( s

  • 8/12/2019 C++Lect1

    6/16

    C++ Lecture 1 OOP

    1.7. Register variables

    A frequently used variable may be allocated in a free register in order to increasethe speed of execution of a program. In registers may be stored function parameters orautomatic variables of int , char , or pointer type. In order to store a variable in a register,

    the variable declaration must be preceded by the register keyword:

    register < variableDeclara ion>

    Example:float f ( register int i){ register int n; register char c; ... }

    1.8. Variables definition (initialization)

    Simple variables are initialized by the following declaration:

    variableIdentifier = < Expression>

    Example:

    f l oat f ( i nt n){ i nt i =1;

    i nt m=n/ 2;. . .

    }

    Arrays are initialized by a following declaration:

    < Type> arrayName [ n ] = {< Expression 1 > , ,, }

    Where m n, and if n does not appear in the declaration, then n=m.

    Example:i nt X [ 13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};i nt Y [] = {1, 2, 3, 4, 5, 6, 7};i nt A[ 3 ] [ ] ={{1, 2, 3}, {4, 5}, {6}}; / / {{1, 2, 3}, {4, 5, ?}, {6, ?, ?}}

    String of characters are initialized by a following declaration:

    char stringName [n] = "string of chars "

    and n may be omitted.

    Example:char message [ 100] = "Al ea i act a est . . . ";char _message[ ] = {". . . al ea i acta est . . . ! "};

    23.03.06 6

    char message_[ ] =al ea i act a est ! " ;

  • 8/12/2019 C++Lect1

    7/16

    C++ Lecture 1 OOP

    2. Expressions

    The basic units of an expression are operands, operators and parenthesis for priority, and every expression has a type and value associated. Left to right does operatorassociation, excepting unary and assigning operators (which is done by right to left).

    Operands can be constants, symbolic constants, simple or structured variables(arrays, structures or their elements), functions or function calls.

    2.1. Operators

    Operators , in decreasing order of priority are the following:

    ( ) [ ] (unary ) +

    (unary ) * (unary ) & (unary ) ! ~ ++ (type) sizeof

    * / % + > < = > = = != & ^ | && | | ?: ( ) ternary

    Arithmetic Operators are the following:

    + , , * , / , % ( mod ), for addition, subtraction, multiplication, division, remainder.

    i nt i , j ;

    = *=

    ,

    /= %= += = =

    &= ^= |=

    Example:

    i nt cat = i / j ; / / 13 / 5 = 2i nt r est = i % j ; / / 13%5 = 3f l oat a=5, b=2;f l oat c=a/ b; / / 5 / 2 = 2. 5

    Comparison operators are the following:

    =, = =, !=, for , , =, .

    The value of the relational expression is 1 for true and 0 for false .Example:

    23.03.06 7

  • 8/12/2019 C++Lect1

    8/16

  • 8/12/2019 C++Lect1

    9/16

    C++ Lecture 1 OOP

    with the signification: = < Variable> ;

    v = e = 2. 7181828; / / v = ( e = 2. 7181828) ;Examples:

    x += dx; y = dy; / / x = x+dx; y = y dy;n ;

    / / t he val ue i ncr ease or decr ease bef or e thei r s usi

    in postfix form: ++;

    / / t he val ue i ncrease or decrease af t er t hei r s u

    a = b ; / / a=b; b=b 1;

    Explicit conversion operators (expression cast ) converts an operand in a certain type:

    Examples:i nt a=12; i nt b=5;

    ( ) < operand > ;

    f l oat c=a/ b;pr i nt f ( " a Di v b = %5. 2f \ n", c) ; / / a Di v b = 2. 00c=( f l oat ) a/ b;pr i nt f ( " a / b = %5. 2f \ n" , c) ; / / a / b = 2. 40

    Implicit conversions (automat realized) are:

    e,

    uble , double )=double ,

    gned )=unsigned .

    In C the explicit conversion is done by ( ) < operand > ; but in C++ it can be done

    ( < operand >) ;

    a) char int , b) float doubl c) (double , *)(dod) (long , *)(long , long )=long ,e) (unsigned , *)(unsigned , unsi

    23.03.06 9

    also by

  • 8/12/2019 C++Lect1

    10/16

    C++ Lecture 1 OOP

    Example:#i ncl ude #i ncl ude #i ncl ude ;voi d mai n (voi d){ char c;

    cout > c;cout

  • 8/12/2019 C++Lect1

    11/16

    C++ Lecture 1 OOP

    #i ncl ude #i ncl ude unsigned x; / / gl obal vari abl es (:: )char y[10];i nt i =99;voi d mai n (voi d){ cl rscr();

    unsi gned x; / / l ocal vari abl esi nt y;cout ::x >>x;cout

  • 8/12/2019 C++Lect1

    12/16

    C++ Lecture 1 OOP

    s - string (ASCII code sequence ending with \0= NUL ) sequence of

    double external decimal [m[.n]], implicitly n=6,0e),

    The printf function returns the number of printed bytes if the operation was perform

    i f ( EOF == printf ( Control , < List of arguments>) ) ; / / . . . ERROR...

    xample:shor t Day=1; char Mont h [ ] =" J anuar y"; unsi gned Year =2003;

    characters, f - float or

    e - float or double external decimal in exponential form ( b*1 E - float or double external decimal in exponential form ( b*10 E ), g - chooses shorter representation between f or e, G - chooses shorter representation between f or E .

    ed successfully, otherwise it will returns -1 (EOF):

    E

    f l oat Hei ght =1. 8;pr i nt f ( " day: %d, mont h: %3. 3s. , year: %u \ n", Day, Mont h, Year) ;

    / / day: 1, mont h: J an. , year : 2003pr i nt f ( " hei ght ( m) : %4. 2f \ n", Hei gt h) ;

    / / hei ght ( m) : 1. 80

    3.2. scanf

    ads data from the standard input and stores it into the locationsgiven b

    , );

    This function rey address of arguments.

    int scanf (Control

    Locations pointed ding type of value

    r printf function, but the conversions are in reverse

    by each argument are filled with their corresponrequested in the format string. There must be the same number of type specifiers in formatstring (control) that arguments passed.

    The format tags are similar to those foorder:

    % [*] [m] [ l] [ f ] ,

    where:

    [*] - is an optional character,ngth of the field,

    long , one of the following

    - int external decimal,

    cimal (0...9,a...f),

    ers ended by blank or m width,

    [m] - specifies the maximum le [ l ] - conversion is done from the internal format [ f ] - determines the type of the conversion, specified by

    characters: d o - int external octal, x - int external hexade X - int external hexadecimal (0...9,A...F), u - unsigned external unsigned decimal,

    c - internal

    binary character,

    s - string sequence of charact

    23.03.06 12

    f - float external floating point.

  • 8/12/2019 C++Lect1

    13/16

    C++ Lecture 1 OOP

    The address of the input variables are given by the address operator & placed infront of

    cessary for arrays!!) .

    Exampshort Day; char Mont h [ 13] ; unsi gned Year; f l oat H;

    each simple variable:

    [&] Variable (is not ne

    le:

    scanf ( " %d %s %u %f " , &Day, Mont h, &Year , &H) ; / / 1 J anuar y 2003 1. 80

    The ields. The end of file(Ctrl/Z

    f ( EOF = = scanf ( Control , < List_of_variables> ) ) ; / / . . . EOF . . .

    xample:i f ( EOF==scanf ( " %d%s%u%f " , &Day, Mont h, &Year , &H) ) pr i nt f ( " Ct r l / Z") ;

    function scanf returns the numbers of the correct read f ) can be verified by the returned value of EOF:

    i

    E

    el se {pr i nt f ( " day: %d, mont h: %3. 3s. , year: %u \ n", Day, Mont h, Year ) ;pr i nt f ( "hei ght ( m) : %4. 2f \ n", H) ;

    }

    3.3. putchar

    a character whose ASCII code is given through an expression:This function prints putchar ( ) ;

    3.4. getchar

    ns the ASCII code of the read character (for Ctrl/Z EOF = 1):This functions retur int getchar ( ) ;

    Example:char c;do put char ( ( ( c=get char ( ) ) >' Z' ) ? c ' ' : c) ;

    / / s mal l l et t er s Capi t al s l et t er s whi l e ( c ! =' . ' ) ; / / i t i s endi ng wi th .

    Litere mici in Litere MARI ! getchar LITERE MICI IN LITERE MARI ! putchar Se termina la . (Punct) getchar SE TERMINA LA . putchar

    3.5. getch

    eturns directly the code of the read character and prints it (withecho).

    e

    This function r

    int getche ();

    23.03.06 13

    Example:

    do put char ( ( ( c=get che( ) ) >' Z' ) ? c ' ' : c);

    whi l e ( c ! =' . ' ) ; / / ends wi t h .

  • 8/12/2019 C++Lect1

    14/16

    C++ Lecture 1 OOP

    L L i I t T e E r R e E m M i I c C i I i I n N L L i I t T e E r R e E M M A A R R I I . .

    3.6.

    rns directly the code of the read character, without printing it:

    getch

    The function retuint getch ();

    Exampi nt r ea

    le:dKey( )

    {i nt car =get ch( ) ;i f ( c ar ) r et ur n car ;el se ret ur n get ch( ) ; / / a f unct i onal key has been pr essed ( 0, cod ASCI I )

    }

    3.7.

    urns the keyboard state (it signals if any key has been pressed):

    kbhit

    This function ret

    int kbhit ( );

    Examp#i ncl ude

    le:

    #i ncl ude #i ncl ude #i ncl ude voi d mai n ( ){ char c [ 8] , i =- 1;

    cout

  • 8/12/2019 C++Lect1

    15/16

    C++ Lecture 1 OOP

    operato

    ncl ude < iostream . h>

    rs: >> (for cin ), respectively i ;

    cout

  • 8/12/2019 C++Lect1

    16/16

    C++ Lecture 1 OOP

    23.03.06 16

    5. Bibliography

    1. Dan Roman , Ingineria program rii obiectuale , Editura Albastr , Cluj_Napoca, 1996;

    2. Dorin & Ioan Mircea Popovici, Iustin Tanase , Tehnologia orientat pe obiecte.

    Aplica ii, Editura Teora, Bucure ti, 1996;

    3. Ellis Horowitz, Sartaj Sahni, Dinesh Metha , Fundamentals of data structures in

    C ++ , Computer Science Press, New York, 1995;

    4. Liviu Negrescu , Limbajele C i C ++ pentru ncep tori, Editura Albastr ,

    Cluj_Napoca, 1997;

    5. Thomas A. Standish , Data Structures, Algorithms & Software Principles in C ,

    Addison-Weslay, California, 1995;

    6. Vasile Cioban, Zsolt Darvay , Metode evoluate de programare , UBB-Mate_Info,

    1999;