Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 2 Introduction to Computer Programming/ C Programming Language 1 EKT120: Computer Programming.

Similar presentations


Presentation on theme: "Week 2 Introduction to Computer Programming/ C Programming Language 1 EKT120: Computer Programming."— Presentation transcript:

1 Week 2 Introduction to Computer Programming/ C Programming Language 1 EKT120: Computer Programming

2 Outline Pseudo code & flowchart Sample programming question Sample C program Identifiers and reserved words Program comments Pre-processor directives Data types and type declarations Operators Formatted input and output Program debugging 2 EKT120: Computer Programming

3 Sample Programming Question Write a program that calculates area of triangle. Your program should read the base length and the height length from user. Given the formula to calculate the area of triangle: 0.5 x (base) x (height). Steps: Analyze the problem Use algorithm Convert to actual codes 3 EKT120: Computer Programming

4 Recall..Pseudo code and Flowchart Try develop the pseudo code and flowchart for the problem given in the previous slide. 4 EKT120: Computer Programming

5 Sample C Program /*Program name : program1.c Programmer : Yasmin This program calculates the area of triangle*/ #include int main(void)‏ { double dBase, dHeight, dArea; printf(“Enter base length : “); scanf(“%f”, &dBase); printf(“Enter height length : “); scanf(“%f”, &dHeight); dArea=0.5 * dBase * dHeight; printf(“\nArea of the triangle is : %5.2f\n”, dArea); return 0; } 5 The term void indicates we receive nothing from OS and return an integer to OS Variables declaration begin end return 0 (int) to OS body Comments Preprocessor directives EKT120: Computer Programming

6 Variables & Reserved Words Identifiers/Variables labels for program elements case sensitive can consist of capital letters[A..Z], small letters[a..z], digit[0..9], and underscore character _ First character MUST be a letter or an underscore No blanks Reserved words cannot be variables/identifiers Reserved words already assigned to a pre-defined meaning e.g.: delete, int, main, include, double, for, if, etc. 6 EKT120: Computer Programming

7 Variables & Reserved Words 7  An identifier for the data in the program  Hold the data in your program  Is a location (or set of locations) in memory where a value can be stored  A quantity that can change during program execution EKT120: Computer Programming

8 Constants A constant is a named or unnamed value, which does not change during the program execution. Example: const double dPi=3.141592 Const int iDegrees=360; Const char cQuit=‘q’; Unnamed constant are often called literals Eg: 3.141592 and 360 8 EKT120: Computer Programming

9 Program Comments Starts with /* and terminates with */ OR Character // starts a line comment, if several lines, each line must begin with // Comments cannot be nested /* /* */*/ 9 EKT120: Computer Programming

10 Preprocessor Directives An instruction to pre-processor Standard library header:, E.g. #include for std input/output #include Conversion number-text vise-versa, memory allocation, random numbers #include string processing 10 EKT120: Computer Programming

11 Data Types 11  Data types determine the following:  Type of data stored  Number of bytes it occupies in memory  Range of data  Operations that can be performed on the data  Modifiers alter the meaning of the base type to more precisely fit a specific need  C supports the following modifiers along with data types:  short, long, signed, unsigned EKT120: Computer Programming

12 Data Types & Memory Allocation 12 TypeBitsBytesRange Char or Signed Char81-128 to +127 Unsigned Char810 to +255 Int or Signed int324-2,147,483,648 to +2,147,483,647 Unsigned int3240 to +4,294,967,295 Short int or Signed short int162-32,768 to + +32,767 Unsigned short int1620 to +65,535 Long int or signed long int324-2,147,483,648 to +2,147,483,647 Unsigned long int3240 to +4,294,967,295 Float3243.4 e-38 to 3.4 e+38 Double6481.7e-308 to 1.7e+308 Long Double6481.7e-308 to 1.7e+308 EKT120: Computer Programming

13 Variables Naming Conventions 13  Variable names should use Hungarian notation  Start with an appropriate prefix that indicates the data type  After the prefix, the name of variable should have more or more words  The first letter of each word should be in upper case  The rest of the letter should be in lower case.  The name of variable should clearly convey the purpose of the variable EKT120: Computer Programming

14 Naming Variables According to Standards 14 PrefixData TypeExample iint and unsigned intiTotalScore ffloatfAverageScore ddoubledHeight llong and unsigned longlFactorial csigned char and unsigned charcProductCode aiArray of integeraiStudentId afArray of floatafWeight adArray of doubleadAmount alArray of long integeralSample acArray of charactersacMaterial EKT120: Computer Programming

15 Data Types Declaration float fIncome; float fNet_income; double dBase, dHeight, dArea; int iIndex =0, iCount =0; char cCh=‘a’, cCh2; const float fEpf = 0.1, fTax = 0.05; 15 float income, net_income; Declare and initialize Named constant declared and initialized

16 Types of Operators Types of operators are: Arithmetic operators (+, -, *, /, %)‏ Relational operators (>, =, <=, !=)‏ Logical operators (&&, ||)‏ Compound assignment operators (+=, -=, *=, /=, %=)‏ Binary operators: needs two operands Unary operators: single operand Bitwise operators: executes on bit level 16 EKT120: Computer Programming

17 Arithmetic Operators Used to execute mathematical equations The result is usually assigned to a data storage (instance/variable) using assignment operator ( = )‏ E.g. sum = marks1 + marks2; 17 EKT120: Computer Programming

18 Arithmetic Operators 18 r % s r mod s % Remainder (Modulus)‏ x / y / Division b * m bm * Multipication p - c p – c - Subtraction f + 7 + Addition C ExpressionAlgebraic Expression Arithmetic Operator C Operation EKT120: Computer Programming

19 Exercise on Arithmetic Operators Given x = 20, y = 3 z = x % y = 20 % 3 = 2 (remainder)‏ 19 EKT120: Computer Programming

20 Relational and Logical Operators Previously, relational operator: >, =, <=, ==, != Previously, logical operator: &&, || Used to control the flow of a program Usually used as conditions in loops and branches 20 EKT120: Computer Programming

21 More on relational operators Relational operators use mathematical comparison (operation) on two data, but give logical output e.g.1 let say b = 8, if (b > 10)‏ e.g.2 while (b != 10)‏ e.g.3 if (mark == 60) print (“Pass”); Reminder: DO NOT confuse == (relational operator) with = (assignment operator)‏ 21 EKT120: Computer Programming

22 More on logical operators Logical operators are manipulation of logic. For example: i. b=8, c=10, if ((b > 10) && (c<10))‏ ii. while ((b==8) || (c > 10))‏ iii. if ((kod == 1) && (salary > 2213))‏ 22 EKT120: Computer Programming

23 Truth Table for && (logical AND) Operator 23 true false true falsetruefalse exp1 && exp2exp2exp1 EKT120: Computer Programming

24 Truth Table for || (logical OR) Operator 24 true falsetrue false exp1 || exp2exp2exp1 EKT120: Computer Programming

25 Compound Assignment Operators To calculate value from expression and store it in variable, we use assignment operator (=)‏ Compound assignment operator combines binary operator with assignment operator E.g. val +=one; is equivalent to val = val + one; E.g. count = count -1; is equivalent to count -=1; count--; --count; 25 EKT120: Computer Programming

26 Unary Operators Obviously operating on ONE operand Commonly used unary operators Increment/decrement { ++, -- } Arithmetic Negation { - } Logical Negation { ! } Usually using prefix notation Increment/decrement can be both a prefix and postfix 26 EKT120: Computer Programming

27 Comparison of Prefix and Postfix Increments 27 EKT120: Computer Programming

28 Unary Operators (Example)‏ Increment/decrement { ++, -- } prefix:value incr/decr before used in expression postfix:value incr/decr after used in expression 28 val=5; printf (“%d”, ++val); Output: 6 val=5; printf (“%d”, val++); Output: 5 val=5; printf (“%d”, --val); Output: 4 val=5; printf (“%d”, val--); Output: 5 EKT120: Computer Programming

29 Operator Precedence 29 last= seventh|| sixth&& fifth== != fourth = > third+ - (binary operators) second* / % first! + - (unary operators) PrecedenceOperators EKT120: Computer Programming

30 Formatted Output with “printf” #include void main (void) { int iMonth; float fExpense, fIncome; iMonth = 12; fExpense = 111.1; fIncome = 1000.0; printf (“Month=%2d, Expense=$%9.2f\n”,iMonth,fExpense); } 30 Declaring variable (fMonth) to be integer Declaring variables (fExpense and fIncome) to be real Assignment statements store numerical values in the memory cells for the declared variables Correspondence between variable names and %...in string literal ‘, ’ separates string literal from variable names EKT120: Computer Programming

31 Formatted Output with printf-cont 31 EKT120: Computer Programming

32 Formatted input with scanf 32 EKT120: Computer Programming

33 Formatted input with scanf-cont 33 EKT120: Computer Programming

34 Program debugging Syntax error Syntax error Mistakes caused by violating “grammar” of C C compiler can easily diagnose during compilation Run-time error Run-time error Called semantic error or smart error Violation of rules during program execution C compiler cannot recognize during compilation Logic error Logic error Most difficult error to recognize and correct Program compiled and executed successfully but answer wrong 34 EKT120: Computer Programming

35 Program debugging-syntax error snapshot 35 EKT120: Computer Programming

36 Program debugging-run time error snapshot 36 EKT120: Computer Programming

37 Program debugging-logic error snapshot 37 EKT120: Computer Programming

38 End Week 2 38 EKT120: Computer Programming Q & A!


Download ppt "Week 2 Introduction to Computer Programming/ C Programming Language 1 EKT120: Computer Programming."

Similar presentations


Ads by Google