chapter2 introductory concepts

Upload: fotress-dazelz

Post on 13-Oct-2015

16 views

Category:

Documents


2 download

DESCRIPTION

zzzz

TRANSCRIPT

  • Chapter 2INTRODUCTORY CONCEPTSElectrical Engineering Department MOHD NASRI BIN HASHIM

    Faculty of Information Technology and Multimedia, 2008/2009

    Learning Outcomes:Understand Constants and VariablesUnderstand Data TypesUnderstand Operators and Expressions

    EC201 Fundamental Programming

    Faculty of Information Technology and Multimedia, 2008/2009

    KeywordintThe acronym for integervoidRefer to the function that will not return any valuecase default switch break

    for continue float double

    return while if do int Example: EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    IdentifierRepresenting particular name in programmingStore values to be used in programmingRefers to the storage in computerStandard identifierUser-definedidentifierType EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Special built-in wordsReferred as function name which will called from C libraryStandardidentifierprintf() scanf()puts() gets()Identifier EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Example..#include #include #define PI 3.142//define the constant value, PI=3.142

    void main(){float radius, area;

    printf("\nEnter radius: ");scanf("%f",&radius); area = PI * radius * radius;printf("Area = %.2f \n",area);printf("Press a key to finish.\n");getch();//to handle the screen} EC201 Fundamental Programming

    Faculty of Information Technology and Multimedia, 2008/2009

    Name given to the declaration of data to be used in program Refer to the storage nameStore data values/result/outputUser-definedidentifierConstantVariableTypeIdentifier EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    User-definedidentifier

    Identifiers name can only consists of name, number and underscoreIdentifiers name cannot be started with numbersSymbol cannot be used in identifier nameCannot contains spaces between two identifiers nameIdentifiers name should be uniqueIdentifiers is not case sensitive

    RULESIdentifier EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    UThM DIT1064 Seven_elevenintegerValid identifiers8Century BIT 1033 Two*four Sixsense voidInvalid identifiersIdentifierExample:WHY?WHY?WHY?WHY?WHY? EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Name which used to store data valueRefer to name of one cell in computer storageContants value is fixedConstantIdentifierHow to give name to a constant value?Follow identifiers rules EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    const data_type const_name = const_value;Declaration format:

    const float pi = 3.142;Reserved wordData type1Constant nameConstant Value EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    #define const_name const_value;Declaration format:

    #define pi 3.142;Reserved word2Constant nameConstant value EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Example.. EC201 Fundamental Programming

    Faculty of Information Technology and Multimedia, 2008/2009

    #define minimum 0;#define MAX 100;

    const int counter = 100;const char alphabet = J;const float value = 4.5;

    Example of constant: EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    data_type variable_name;Name which used to store data/input valueRefer to the name of one cell in computer storageVariables value can be modified/changed during executionVariableDeclaration Format: Identifier EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Declaration Example

    int number;

    float weight;

    char alphabet;Declaration of a variable number of integer data type.Declaration of a variable weight offloating point data type.Declaration of a variable alphabet of character data type. EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Variable/constant declaration example //Variable and constant declration#include

    int number;float weight;

    void main(){ const float pi =3.142;

    int bilangan; float berat; char abjad; }Constant declarationVariable declarationVariable declaration EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Variable and constant declaration example: //Variable and constant declaration#include

    const float pi=3.142;

    void main(){ int bilangan, bil, bilang; float berat, kg; char A; } EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Assigning value to variables #include

    void main(){ int number = 10; float weight; weight = 60.00;

    printf(Enter the value of number :); scanf(%d,&number);

    number = 50.00;}

    Initialize a variableInteractiveExample:Initialize a variable EC201 Fundamental ProgrammingConstants and Variables (Identifier)

    Faculty of Information Technology and Multimedia, 2008/2009

    Represents types of data can be stored in computer.Types of data to be stored and used in programming should be informed to the compiler/system TypesIntegerFloatingpointCharacterData Types EC201 Fundamental ProgrammingData Types

    Faculty of Information Technology and Multimedia, 2008/2009

    Data TypesRepresents any round number with +/- values.Divided into short and long integer.Reserved word for integer intValid until 5 places of integer number.IntegerExample:age is used to represent the age of students between 18 and 25 years old. The declaration for thevariable is as follow:

    int age; EC201 Fundamental ProgrammingData Types

    Faculty of Information Technology and Multimedia, 2008/2009

    Data TypesRepresents any floating point numbers +/-Reserved word double /floatFloating numberExample:height is used to represent the students height between 150 cm and 180 cm. The declaration for thevariable is as follow:

    float height; EC201 Fundamental ProgrammingData Types

    Faculty of Information Technology and Multimedia, 2008/2009

    Data TypesRepresents character data.Reserved word charCharacterExample:gender is used to represent the gender of a student. The declaration for the variable is as follow: char gender; EC201 Fundamental ProgrammingData Types

    Faculty of Information Technology and Multimedia, 2008/2009

    Determine whether the following identifiers is valid or invalid. Give reason for invalid cases.1)Parit Raja 2)20thCentury 3) int 4)INTEGER5)_BMW20036)Reservedword7)BIT10338)markah_pelajar9)jam*kredit10)printf

    Exercise: EC201 Fundamental ProgrammingExample..

    Faculty of Information Technology and Multimedia, 2008/2009

    Write a suitable variable declaration for each of the following statement:

    i.Salary of an employeeii.Students mark for programming subjectiii.ATM pin numberiv.Phone number v. Price of one item vi. Bus seat number vii. Student name

    Exercise: EC201 Fundamental ProgrammingExample..

    Faculty of Information Technology and Multimedia, 2008/2009

    Given the value of x is 10 and a is 12, find the result of the following equation:

    y = 2x + a - 6 Based on the following problem, determine the appropriate variables can be declared:Exercise: EC201 Fundamental ProgrammingExample..

    Faculty of Information Technology and Multimedia, 2008/2009

    Mrs Leeya needs to determine her students grade for programming subject based on the mark scored duringfinal examination. The A grade will be given if the markscored is between 85 to 100. If a student has scored 90 marks, what is the grade should Mrs Leeya give to thestudent? Based on the following problem, determine the appropriate variables can be declared:Exercise: EC201 Fundamental Programming

    Example..

    Faculty of Information Technology and Multimedia, 2008/2009

    Based on the following problem, determine the appropriate variables can be declared:Exercise:A box has height, width and length. Calculate the volume of a box. EC201 Fundamental ProgrammingExample..

    Faculty of Information Technology and Multimedia, 2008/2009

    Uncle Degawan wants to buy 5 tins of paint from Cindas shop. The price of each tin of the paint is RM 15.60. Calculate the price which Uncle Degawan haveto pay for all the tin of paints he bought.

    Based on the following problem, determine the appropriate variables can be declared:Exercise: EC201 Fundamental ProgrammingExample..

  • *Operators and Expressions

    Faculty of Information Technology and Multimedia, 2008/2009

    Expressions EC201 Fundamental Programming

    Faculty of Information Technology and Multimedia, 2008/2009

    a) Operand A quantity or function upon which a mathematical or logical operation is performed EC201 Fundamental ProgrammingOperators and Expressions

    Faculty of Information Technology and Multimedia, 2008/2009

    b) Operator An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on data and variables. C has a rich set of operators which can be classified as

    EC201 Fundamental ProgrammingOperators and Expressions

    Faculty of Information Technology and Multimedia, 2008/2009

    i. Arithmetic- All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number 5 when operated by unary will have the value 5 EC201 Fundamental ProgrammingOperators and Expressions

    Operator Meaning + Addition or Unary Plus Subtraction or Unary Minus * Multiplication / Division % Modulus Operator

    Faculty of Information Technology and Multimedia, 2008/2009

    Example : There are two integer variables a and b. If the starting value of a=7 and b=2, the result will be:Operators and Expressions EC201 Fundamental Programming

    ExpressionValuea b5a + b9a * b14a / b3a % b1

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and ExpressionsInteger Arithmetic When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers. Then the integer operation leads to the following results. x + y = ? x y = ? x * y = ? x % y = ? x / y = ? In integer division the fractional part is truncated

    32221152

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressionsii. Relational OperatorOften it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when the relational operator come into picture. C supports the following relational operators.

    OperatorMeaning < is less than is greater than >= is greater than or equal to == is equal to != is not equal to

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and ExpressionsGiven below is a list of examples of relational expressions and evaluated values. 6.5 0 FALSE 10 < 7 + 5 TRUE ** The result of evaluation of a relational operation is either True (represented by 1) or false (represented by 0).

    For example, if a = 7 and b = 5, then a < b yields 0 and a != b yields 1.

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressionsiii. Logical OperatorC has the following logical operators, they compare or evaluate logical and relational expressions.

    OperatorMeaning&&AND||OR!NOT

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and ExpressionsLogical AND (&&) This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true. Example a > b && x = = 10 The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10. Logical OR (||) The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true. Example a < m || a < n The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and ExpressionsLogical NOT (!) The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression. For example ! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y

    Faculty of Information Technology and Multimedia, 2008/2009

    The result of logical operation on a and b are summarized as below:-Operators and Expressions EC201 Fundamental Programming

    VariableExpressionABA && BA || B!A TTTTFTFFTFFTFTTFFFFT

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressions4. Assignment OperatorsC provides several assignment operators for abbreviating assignment expressions. For example the statementc = c + 3;can be abbreviated with the addition assignment operator += asc += 3;The += operator adds the value of expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator. Any statement of the formVariable = variable operator expression;Where operator is one of the binary operators +, -, *, / or %, can be written in the formVariable operator = expression;Thus the assignment c += 3 adds 3 to c. Table shows the arithmetic assignment operators, sample expressions using these operators and explanations.

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressions

    Assignment operatorSample expressionExplanationAssignsAssume: int c = 3, d = 5, e = 4, f = 6, g = 13+=c += 7c = c + 710 to c-=d -= 4d = d 41 to d

    Assignment operatorSample expressionExplanationAssigns*=e *= 5e = e * 520 to e/=f /= 3f = f / 32 to f%=g %= 9g = g % 93 to g

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressions5. Increments and Decrement Operators

    OperatorSample expressionExplanation++++aIncrement a by 1 then use the new value of a in the expression in which a resides++a++Use the current value of a in the expression in which a resides, the increment a by 1 (Still remain same number) ----bDecrement b by 1 the use the new value of b in the expression in which b resides--b--Use the current value of b in the expression in which b resides, then decrement b by 1 (Still remain same number)

    Faculty of Information Technology and Multimedia, 2008/2009

    EC201 Fundamental ProgrammingOperators and Expressions5. Increments and Decrement Operators

    #include int main(void);{int j = 5, k = 5, l = 5, m = 5;printf("j: %d\t k: %d\n", j, k);printf("j: %d\t k: %d\n", j++, k--);printf("l: %d\t m: %d\n", l, m);printf("l: %d\t m: %d\n", ++l, --m);}

    Output:j: 5 k: 5j: 5 k: 5l: 5 m: 5l: 6 m: 4

    Faculty of Information Technology and Multimedia, 2008/2009

    HIERARCHY OF OPERATORThe hierarchy of operator precedence form highest to lowest is summarized below:

    EC201 Fundamental Programming

    Operator CategoryOperatorUnary- - - + +Arithmetic multiply, devide, remainder* / %Arithmetic add and subtract+ -Relational operators< >=Equality operators= = ! =Logical AND&&Logical OR||

    Faculty of Information Technology and Multimedia, 2008/2009

    Find the answer using the hierarchy of operator.Use: a=12, b=2, c=3a) X = a % bb) X = a /bc) X = a % b / cd) X = a / b % c EC201 Fundamental ProgrammingExercise:Example..

    Faculty of Information Technology and Multimedia, 2008/2009

    EXERCISE 1:

    int a=5, b=2, c=3, d=4;float answer;

    answer = (a % c)* (d+b) * d / (a-c);printf("The answer is : %.3f",answer);printf("\n");

    EXERCISE 2: int m;int a=100, b=5, c=3, d=2, x=3;m = a + b * c / d x++;printf(The answer is : %d",m);printf(/n);

    Example..Exercise: EC201 Fundamental Programminganswer=24m=104

    Faculty of Information Technology and Multimedia, 2008/2009

    Consider the following example: 2*3+4/2 > 3 AND 3