meljun cortes--it102 intro turbo c computing

Upload: meljun-cortes-mbampa

Post on 10-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    1/68

    CMPE 150: Introduction toComputing

    MELJUN CORTES,BSCS,ACS

    Introduction

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    2/68

    Fall 2008 CMPE 150 Introduction to Computing 2

    Basic info about the course

    Aim: To teach basic programming skills Course web site:

    http://www.cmpe.boun.edu.tr/courses/cmpe150/fall2008

    There is no difference between the sections.

    There are some changes in the organization ofthe course.

    5 hours of class every week

    1 hour lecture and 2 hours PS (lectured by theinstructor)

    2 hours lab (taught by an assistant; studentassistants will also help the assistant)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    3/68

    Fall 2008 CMPE 150 Introduction to Computing 3

    VERY IMPORTANT NOTICE All announcements are made through the CMPE150 e-mail list. The

    list has been constructed using your e-mail addresses in theRegistration system. Make sure that your address in theRegistration system is:your BOUN address,you check it every day,its quota is not exceeded and it is functional.

    (We will re-construct the list after the add-drop period is over, sochange it now if your Registration e-mail address is not from BOUN.) Note that Yahoo, GMail, Hotmail, and similar addresses frequently

    have problems or the messages may go to the spam folder. It is completely your responsibility to make sure that your account

    receives the messages properly. We will send the announcements

    via the mailing list and assume you read it the same day. There aremore than 350 students in this course and we do not have anyadditional means to contact you if your e-mail address is notworking.

    NO EXCUSES WILL BE ACCEPTED FOR AN ANNOUNCEMENTALREADY MADE THROUGH THE MAILING LIST.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    4/68

    Fall 2008 CMPE 150 Introduction to Computing 4

    Basic info about the course

    You will have 2 midterms

    1 final

    3 projectsthroughout the semester.

    The projects are NOT mandatory (except

    for CMPE students). However, there willbe a question closely related with theproject in every exam.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    5/68

    Fall 2008 CMPE 150 Introduction to Computing 5

    Grading

    Midterm 1 30% Midterm 2 30%

    Final 40%

    CMPE students start with -15 points To compensate for this, they have to submit

    all of their projects.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    6/68

    Fall 2008 CMPE 150 Introduction to Computing 6

    Exams and labs

    The exams are in front of the computer. Youwill use our online compiler in the exams.

    You will use the same online compiler also in thelabs. THEREFORE, YOU MAY CONCLUDE

    THAT YOU WILL NOT DO WELL IN THEEXAMS IF YOU DO NOT ATTEND THELABS.

    No attendance taken in class or lab. However, we STRONGLYrecommend that youattend the labs.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    7/68

    Fall 2008 CMPE 150 Introduction to Computing 7

    Exams and labs

    You will be assigned a username andpassword for the online compiler. In the exams, you will receive an

    additional password. It is yourresponsibility to ensure that no one elsesees this password. NO MERCY ABOUTCHEATING.

    We do not increase (or even decrease)your letter grades at the end of thesemester. Dont ask for it.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    8/68

    Fall 2008 CMPE 150 Introduction to Computing 8

    Course outline1- Introduction, printf, scanf, variables, operators, constants

    2- Data types, assignment type conversions, type casting, post/pre-increment, type casting

    3- If, nested if, logical operators, switch4- While, for, do-while5- Nested loops, break, continue

    6- Functions, scope, macro-substitution7- Pointers, variable parameters (aka. call by reference or pointers asfunction arguments)

    8- Arrays, passing arrays to functions, sorting and binary search9- Strings10- Multi-dimensional arrays

    11- Structs12- Review

    Note that pointers (except for variable parameters) are notincluded) in CMPE150 anymore.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    9/68

    Fall 2008 CMPE 150 Introduction to Computing 9

    Lets get started !

    We will first learn how a computeroperates.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    10/68

    Fall 2008 CMPE 150 Introduction to Computing 10

    A computer system

    A computer system is composed of: a monitor, a keyboard, a mouse, and a case (that contains several

    controlling components such asprocessor and alike), and also other peripherals like

    CD player (might have been includedin the case),

    printer,

    scanner, modem, etc.

    all connected together

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    11/68

    Fall 2008 CMPE 150 Introduction to Computing 11

    Input and output devices

    InputInput

    Input

    InputInput

    OutputOutput

    /Output

    /Output

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    12/68

    Fall 2008 CMPE 150 Introduction to Computing 12

    A computer system

    Note that everything could be packed in asingle box, but the concepts are thesame.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    13/68

    Fall 2008 CMPE 150 Introduction to Computing 13

    A computer system

    Everything we had in the previous slide ishardware. i.e., physical components that implement what

    is requested by the software.

    HARDWARE

    OPERATING SYSTEM

    (Windows, Linux, MacOS, etc.)

    APPLICATIONS

    (Eg: Word, Excel, Explorer, MSN, C Compiler,

    your own programs, etc.)

    SOFTW

    AR

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    14/68

    Fall 2008 CMPE 150 Introduction to Computing 14

    A computer system

    In this course, we will learn how todevelop our own software (using Clanguage), but we need to understand how

    our programs will be executed by thehardware.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    15/68

    Fall 2008 CMPE 150 Introduction to Computing 15

    CPU: Central Processing Unit

    In terms of hardware, what is importantfor us is the CPU.

    It does all processing and control.

    Everything is controlled and executed by theCPU.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    16/68

    Fall 2008 CMPE 150 Introduction to Computing 16

    CPU: Central Processing Unit

    Control Unit

    Registers

    Arithmetic &

    Logic Unit

    R1

    R2...

    Rm

    IR

    ...

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    17/68

    Fall 2008 CMPE 150 Introduction to Computing 17

    Central Processing Unit (CPU)

    Control Unit

    Registers

    Arithmetic &

    Logic Unit

    How are the instructions executed?

    instr 2

    instr 3

    ...

    instr n

    instr 1

    Program

    Main Memory

    R1

    R2...

    Rm

    IR

    ...

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    18/68

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    19/68

    Fall 2008 CMPE 150 Introduction to Computing 19

    Statement vs. Instruction

    Our source code (in C) is composed ofstatements. Eg: a=b+c/2;

    The corresponding machine code is composed ofinstructions. Eg: 1101001010110010 (divide c by 2) 0110100100100101 (add it to b) 1010110110111011 (put the result in a) CPU is capable of executing instructions, not

    statements. Statements may be too complex. Compiler implements each statement using severalinstructions.

    Eg: The statement "a=b+c/2;" can be implemented astemp1 = c/2a = b + temp1

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    20/68

    Fall 2008 CMPE 150 Introduction to Computing 20

    Why have input/output?

    A program should not always produce thesame output. O/w, you may keep the result and delete the

    program after you run it for the first time.

    A program should be consistent; i.e., itshould not produce random results.

    Therefore, a program should take someinput, process it, and produce someoutput as the result of that input.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    21/68

    Fall 2008 CMPE 150 Introduction to Computing 21

    Execution of an instruction Lets see how an instruction like "a=b+2" is executed.

    Assume initially a is 4 andb is 6.

    Central Processing Unit (CPU)

    Control Unit

    Registers Arithmetic &

    Logic Unit

    ...

    a=b+2

    Main Memory

    R1

    R2...

    Rm

    IR

    ...

    a 4

    b 66

    Program

    ...

    a=b+2 2

    8

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    22/68

    Fall 2008 CMPE 150 Introduction to Computing 22

    Welcome to C Programming Language

    Now that we have an overall understanding ofthe computer, we can start writing C programs. Remember:

    We write our

    programs in

    "C language"(whichis an English-like

    language)

    #include int main(){

    printf("Hello world!");return 0;

    }

    We use a compiler

    (such as GCC, Visual

    C, Borland C, etc.) totranslate our program

    from "C language" to

    "machine language"

    Compile & Link

    This is the executable

    code in "machine

    language."

    This is the only thing

    the computer can

    understand and run

    (execute).

    1110101011001001010001010100101000010010100101010101000101001000100101001

    (source code) (object code)

    (machine code

    or

    executable code)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    23/68

    Fall 2008 CMPE 150 Introduction to Computing 23

    Our first C program: Hello World

    Every C program has amain() function. It wraps all the statements to

    be executed.

    We make use of previouslywritten functions. They areprovided by header files. Typically, we include the

    standard input/output header

    file, named stdio.h. We write all statements

    inside themain() function.

    #include

    int main()

    {

    printf("Hello world");

    return 0;

    }

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    24/68

    Fall 2008 CMPE 150 Introduction to Computing 24

    Need for input Note that the Hello World program has no

    input. Therefore, it always produces the same output:

    Hello World So, after we run this program once, we know what it

    will always produce. Therefore, we dont need theprogram anymore; we can safely delete it. Definitely this is not what we want. (O/w,

    nobody will pay us ) We want to write programs that can take input and

    produce different results according to the input. (Details of I/O functions will be covered in the

    labs.)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    25/68

    Fall 2008 CMPE 150 Introduction to Computing 25

    A program that also performs input

    #include

    int main()

    {

    int a, b, c;

    printf("Enter two numbers: ");

    scanf("%d%d", &a, &b);

    c=a+b;

    printf("Result is %d ", c);return 0;

    }

    Enter two numbers:

    Result is 13

    C Program User screen_

    __

    \n

    58_

    Read two integers

    (decimals) into

    variables a and b

    Display the value

    of variable c after

    the text "Result is"

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    26/68

    Fall 2008 CMPE 150 Introduction to Computing 26

    Variables

    Operations (such as addition, subtraction,etc.) operate on operands.

    You need some space to store the value

    of each operand. A variable provides storage space for avalue.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    27/68

    Fall 2008 CMPE 150 Introduction to Computing 27

    Variables

    IMPORTANT: The value of a variable cannever be empty. The value is representedvia multiple bits, each of which is either 0or 1. So, the variable always has a value.

    When a local variable is defined, its initialvalue is undefined. In other words, it hasan arbitrary value. (For the moment, wewill not use global variables.)

    So, make sure that the variable has avalid value before you perform anyoperation based on that value.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    28/68

    Fall 2008 CMPE 150 Introduction to Computing 28

    Variables Each variable consists of multiple bits. E.g.:

    Thus, every value is actually stored as asequence of bits (1s and 0s) in the computer.

    The number of bits is called the size of thevariable. The size of a variable depends on the type of

    the variable, the hardware, the operatingsystem, and the compiler used.

    So, in your programs NEVER make assumptions aboutthe size of a variable. The size may change due to the factors listed above,

    and your program will not work.

    0 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1 213+210+29+27+25+24+22+21+20=991115 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    29/68

    Fall 2008 CMPE 150 Introduction to Computing 29

    Variables#include

    int main

    {

    int a, b, c;

    a=10;

    b=3;

    c=a-b;

    a=b+2;

    }

    a ...

    Program

    b ...

    c ...

    10

    7

    3

    5

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    30/68

    Fall 2008 CMPE 150 Introduction to Computing 30

    Rules for identifier names While defining names for variables (and also functions,

    user-defined types, and constants in the future) youshould obey the following rules: The first character of a name must be a letter or underscore

    (_). The remaining characters must be letters, digits, or

    underscore. Only the first 31 characters are significant. Avoid reserved words such as int, float, char, etc. as identifier

    names.

    However, it is better to avoid starting identifier nameswith underscore.

    Also remember that C language is case-sensitive. It is a very good practice to use meaningful names.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    31/68

    Fall 2008 CMPE 150 Introduction to Computing 31

    Rules for identifier names

    Valid:a, a1, count, no_of_students, B56, b_56 Invalid:

    1a, say, int, $100

    Valid but not recommended:_b56, Tuna, FB, GS, BJK,I_dont_remember_what_this_variable_means,a_very_very_long_identifier_name_1,

    a_very_very_long_identifier_name_2

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    32/68

    Fall 2008 CMPE 150 Introduction to Computing 32

    Standard data types

    You have to specify the type of a variablewhen you define it.

    There are three standard data types:

    Integer (i.e., whole numbers) Float (i.e., real or floating-point numbers)

    Characters

    We will discuss user-defined types laterin the course.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    33/68

    Fall 2008 CMPE 150 Introduction to Computing 33

    Integers Syntax:

    int variable_list;wherevariable_list is a comma-separated list of variablenames. Each variable name may be followed by an optionalassignment operator and a value for initialization.

    Eg: int a, b=10, c;

    Integer is a class of variable types. The most basic oneis int. The size may change, but the leftmost bit is used for

    the sign. The remaining bits represent the value inbinary.

    Though the size of an int variable may vary, it is alwayslimited, i.e., it contains a limited number of bits.Therefore, the maximum and minimum values that canbe represented by an int variable is limited.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    34/68

    Fall 2008 CMPE 150 Introduction to Computing 34

    Integers

    For example, assume in your system an integerhas 16 bits.

    Leftmost bit is used for the sign, so 15 bits areleft for the value. So, you have 215=32,768positive values, ranging from 0 to 32,767.Similarly, you have 32,768 negative values, this

    time ranging from -1 to -32,768. If you have 32 bits (4 bytes) for an integer,than the maximum value is 231=2,147,483,647.

    0 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1

    sign bit value

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    35/68

    Fall 2008 CMPE 150 Introduction to Computing 35

    Integers

    There are variations of int such as longint, short int, unsigned int. For each one of these types, you may ignore

    the word "int" and use long, short, andunsigned, respectively.

    The sizes of these types are ordered asfollows:

    short int int long int

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    36/68

    Fall 2008 CMPE 150 Introduction to Computing 36

    Floating-point numbers

    Syntax:float variable_list;

    Float type is used for real numbers.

    Note that all integers may berepresented as floating-point numbers,but not vice versa.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    37/68

    Fall 2008 CMPE 150 Introduction to Computing 37

    Floating-point numbers

    Similar to integers, floats also have theirlimits: maximum and minimum values arelimited as well as the precision.

    Lower limit Upper limitThe value you

    want to store

    Due to loss of precision, what you actually

    store might be this, or this

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    38/68

    Fall 2008 CMPE 150 Introduction to Computing 38

    Floating-point numbers

    There are two variations of float:double and long double. They have wider range and higher precision.

    The sizes of these types are ordered asfollows:float double long double

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    39/68

    Fall 2008 CMPE 150 Introduction to Computing 39

    Characters

    Syntax:char variable_list;

    Character is the only type that has a

    fixed size in all implementations: 1 byte. All letters (uppercase and lowercase,

    separately), digits, and signs (such as

    +,-,!,?,$,,^,#, comma itself, and manyothers) are of type character.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    40/68

    Fall 2008 CMPE 150 Introduction to Computing 40

    Characters

    Since every value is represented with bits(0s and 1s), we need a mapping for allthese letters, digits, and signs.

    This mapping is provided by a table ofcharacters and their correspondinginteger values. The most widely used table for this purpose

    is the ASCII table.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    41/68

    Fall 2008 CMPE 150 Introduction to Computing 41

    Characters

    The ASCII table contains the values for256 values (of which only the first 128are relevant for you). Each row of thetable contains one character. The rownumber is called the ASCII code of thecorresponding character.(The topic of character encoding isbeyond the scope of this course. So, wewill work with the simplified definitionhere.)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    42/68

    Fall 2008 CMPE 150 Introduction to Computing 42

    Characters

    Never memorize the ASCII codes. Theyare available in all programming books andthe Internet. (Eg: http://www.ascii-code.com)

    What is important for us is the followingthree rules: All lowercase letters (a,b,c,...) are consecutive.

    All uppercase letters (A,B,C,...) are consecutive.

    All digits are consecutive.

    http://www.ascii-code.com/http://www.ascii-code.com/
  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    43/68

    Fall 2008 CMPE 150 Introduction to Computing 43

    ASCII table (partial)ASCII code Symbol ASCII code Symbol ASCII code Symbol ASCII code Symbol

    ... ... 66 B 84 T 107 k32 blank 67 C 85 U 108 l

    37 % 68 D 86 V 109 m

    42 * 69 E 87 W 110 n

    43 + 70 F 88 X 111 o

    ... ... 71 G 89 Y 112 p

    48 0 72 H 90 Z 113 q

    49 1 73 I ... ... 114 r

    50 2 74 J 97 a 115 s

    51 3 75 K 98 b 116 t

    52 4 76 L 99 c 117 u

    53 5 77 M 100 d 118 v

    54 6 78 N 101 e 119 w

    55 7 79 O 102 f 120 x

    56 8 80 P 103 g 121 y

    57 9 81 Q 104 h 122 z

    ... ... 82 R 105 i ... ...

    65 A 83 S 106 j

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    44/68

    Fall 2008 CMPE 150 Introduction to Computing 44

    Characters

    A character variable actually stores theASCII value of the corresponding letter,digit, or sign.

    I/O functions (printf(), scanf(), etc.) dothe translation between the image of acharacter displayed on the screen andthe ASCII code that is actually stored inthe memory of the computer.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    45/68

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    46/68

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    47/68

    Fall 2008 CMPE 150 Introduction to Computing 47

    Constants Syntax:

    #define constant_name constant_value

    As the name implies, variables store values that varywhile constants represent fixed values.

    Note that there is no storage when you use constants.

    Actually, when you compiler your program, the compilerreplaces the constant name with the value you defined. The pre-processor replaces every occurrence ofconstant_name with everything that is to the right ofconstant_name in the definition. Note that there is no semicolon at the end of the definition.

    Conventionally, we use names in uppercase forconstants.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    48/68

    Fall 2008 CMPE 150 Introduction to Computing 48

    Enumerated type Used to define your own types. Syntax:

    enumtype_name {

    item_name=constant_int_value, ...

    }variable_list;

    By default, the value of the first item is 0, andit increases by one for consecutive items.However, you may change the default value byspecifying the constant value explicitly.

    Eg: enum boolean {FALSE,TRUE} v1, v2;enum days {SUN,MON,TUE,WED,THU,FRI,SAT};

    enum {one=1,five=5,six,seven,ten=10,eleven} num;

    Text in green is optional

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    49/68

    Fall 2008 CMPE 150 Introduction to Computing 49

    Operators

    We will cover the most basic operators in class.More operators will be covered in the labs.

    Assignment operator (=) Note that this is not the "equals" operator. It should

    be pronounced as "becomes." (Equals is anotheroperator.)

    The value of the expression on the RHS is assigned(copied) to the LHS.

    It has right-to-left associativity.a=b=c=10;

    makes all three variables 10.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    50/68

    Fall 2008 CMPE 150 Introduction to Computing 50

    Assignment and type conversion

    When a variable of a narrower type isassigned to a variable of wider type, noproblem. Eg: int a=10; float f;

    f=a;

    However, there is loss of information inreverse direction. Eg: float f=10.9;int a;

    a=f;

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    51/68

    Fall 2008 CMPE 150 Introduction to Computing 51

    Operators Arithmetic operators (+,-,*,/,%)

    General meanings are obvious. What is important is the following: If one of the

    operands is of a wider type, the result is also of thattype. (Its importance will be more obvious soon.)

    Eg: Result of int+float is float. Result of float+double isdouble.

    In C language, there are two types of division: integerdivision and float division.

    If both operands are of integer class, we perform integer

    division and the result is obtained by truncating the decimalpart. Eg: 8/3 is 2, not 2.666667.

    If one of the operands is of float class, the result is float. Eg: 8.0/3 or 8/3.0 or 8.0/3.0 is 2.666667, not 2.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    52/68

    Fall 2008 CMPE 150 Introduction to Computing 52

    Operators

    Remainder operator is %. Both operands mustbe of integer class. Eg: 10%6 is 4 (equivalent to 10 mod 6)

    +,-,*,/,% have left-to-right associativity.

    That means a/b/c is equivalent to(a/b)/c, but not a/(b/c).

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    53/68

    Fall 2008 CMPE 150 Introduction to Computing 53

    Operators

    Logic operators (&&, ||, !) Logic operators take integer class operands. Zero means false.

    Anything non-zero means true.

    "&&" does a logical-AND operation. (True onlyif both operands are true.)

    "||" does a logical-OR operation. (False only

    if both operands are false.) "!" does a negation operation. (Converts true

    to false, and false to true.)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    54/68

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    55/68

    Operators If the first operand of the "&&" operator is false,

    the second operand is not evaluated at all (since itis obvious that the whole expression is false). Eg: In the expression below, if the values ofb and c

    are initially 0 and 1, respectively,

    a = b && (c=2)then the second operand is not evaluatedat all, so c keeps its value as 1.

    Similarly, if the first operand of the "||"

    operator is true, the second operand is notevaluated at all.

    Fall 2008 CMPE 150 Introduction to Computing 55

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    56/68

    Fall 2008 CMPE 150 Introduction to Computing 56

    Operators

    Bitwise operators (&, |, ^, , ~) Bitwise operators take integer class operands. For the logic operators, the variable represents a

    single logical value, true or false.

    For the bitwise operators, each bit of the variablerepresents true or false.

    &, |, and ^ perform bitwise-AND, -OR, -XOR,respectively.

    >perform left- and right-shifts.

    "~" takes bitwise ones complement.

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    57/68

    Fall 2008 CMPE 150 Introduction to Computing 57

    OperatorsOperation Result

    5 & 10(0000 0101 &0000 1010)

    0(0000 0000)

    5 && 10(0000 0101 &&0000 1010)

    1(0000 0001)

    5 | 10(0000 0101 |0000 1010)

    15(0000 1111)

    8 ^ 10(0000 0111 ^0000 1010)

    13(0000 1101)

    7 2(0000 0111 >> 0000 0010)

    1 (0000 0001)

    ~5(~0000 0101)

    -6 (in twos complement)(1111 1010)

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    58/68

    Fall 2008 CMPE 150 Introduction to Computing 58

    Operators

    Other assignment operators (+=, -=, *=,/=, %=) Instead of writing a=a+b, you can write a+=b

    in short. Similar with -=, *=, /=, and others.

    O

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    59/68

    Fall 2008 CMPE 150 Introduction to Computing 59

    Operators

    Pre/Post increment/decrement operators(++, --) The operator ++ increments the value of the

    operand by 1.

    If the operator comes BEFORE the variable name,the value of the variable is incremented beforebeing used, i.e., the value of the expression is theincremented value. This is pre-increment.

    In post-increment, the operator is used after the

    variable name, and incrementation is performedafter the value is used, i.e., the value of theexpression is the value of the variable beforeincrementation.

    O

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    60/68

    Fall 2008 CMPE 150 Introduction to Computing 60

    Operators

    Eg:a=10; c=10,

    b=++a; d=c++;

    Both a and c will be come 11, butbwill be 11 while dis 10.

    O

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    61/68

    Fall 2008 CMPE 150 Introduction to Computing 61

    Operators

    Comparison operators (==,!=,

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    62/68

    Fall 2008 CMPE 150 Introduction to Computing

    Operators

    Symbol Usage Meaning== x == y is x equal to y?

    != x != y is x not equal to y?

    > x > y is x greater than y?

    < x < y is x less than y?

    >= x >= y is x greater than or equal to y?

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    63/68

    Operators

    We can create complex expressions byjoining several expressions with logicoperators.

    Fall 2008 CMPE 150 Introduction to Computing 63

    Symbol Usage Meaning

    && exp1 && exp2 AND

    || exp1 || exp2 OR

    ! ! exp NOT

    O t

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    64/68

    Fall 2008 CMPE 150 Introduction to Computing 64

    Operators

    While using multiple operators in thesame expression, you should be carefulwith the precedence and associativity ofthe operands.

    Eg: The following does NOT check if a isbetween 5 and 10.bool = 5

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    65/68

    Operator precedence table

    Fall 2008 CMPE 150 Introduction to Computing 65

    Operator Associativity

    () [] . -> left-to-right

    ++ -- + - ! ~ (type) * & sizeof right-to-left* / % left-to-right+ - left-to-right

    > left-to-right< >= left-to-right

    == != left-to-right

    & left-to-right^ left-to-right| left-to-right&& left-to-right|| left-to-right?: right-to-left

    = += -= *= /= %= &= ^= |= = right-to-left

    , left-to-right

    O t

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    66/68

    Operators Precedence, associativity, and order of

    evaluation: In the table is given in the previous slide,precedence decreases as you go down.

    If two operands in an expression have the sameprecedence, you decide according to the associativity

    column. There is a common misunderstanding aboutassociativity.

    Note that associativity has nothing to do with the orderof evaluation of the operands.

    Order of evaluation of operands is not specified in Clanguage.

    It is strongly recommended that you read andunderstand Section 2.12 (pp. 52-54) in the bookby Kernighan & Ritchie.

    Fall 2008 CMPE 150 Introduction to Computing 66

    T ti

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    67/68

    Fall 2008 CMPE 150 Introduction to Computing 67

    Type casting

    Also called coersionor type conversion. It does NOT change the type of avariable. It is not possible to change the

    type of a variable. What casting does is to convert the typeof a value.

    T ti

  • 8/8/2019 MELJUN CORTES--IT102 Intro Turbo C Computing

    68/68

    Type casting Eg: int a=10, b=3;

    float f, g;f=a/b;g=(float)a/b;

    The type of a does not change; it is still andinteger. However, in the expression(float)a/b, the value of a, which is 10, isconverted to float value of 10.0, and then it isdivided byb, which is 3. Thus, we perform float

    division and g becomes 3.3333... On the other hand, we perform an integerdivision for f, so it becomes 3.