Week 1 Introduction to Computer and Algorithm Part






































- Slides: 38

Week 1 – Introduction to Computer and Algorithm (Part 2) Uni. MAP Sem I-18/19 DKT 121: Fundamental of Computer Programming 1

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

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

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

Sample C Program /*Program name : program 1. c Programmer : Yasmin This program calculates the area of triangle*/ #include <stdio. h> Comments Preprocessor directives begin int main(void) { double d. Base, d. Height, d. Area; Variables declaration printf(“Enter base length : “); scanf(“%f”, &d. Base); printf(“Enter height length : “); scanf(“%f”, &d. Height); The term void indicates we receive nothing from OS and return an integer to OS d. Area=0. 5 * d. Base * d. Height; printf(“n. Area of the triangle is : %5. 2 fn”, d. Area); return 0; } end body return 0 (int) to OS 5

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

Variables & Reserved Words §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 7

Constants A constant is a named or unnamed value, which does not change during the program execution. Example: const double d. Pi=3. 141592 Const int i. Degrees=360; Const char c. Quit=‘q’; Unnamed constant are often called literals Eg: 3. 141592 and 360 8

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

Preprocessor Directives An instruction to pre-processor Standard library header: <stdio. h>, <math. h> E. g. #include <stdio. h> #include <stdlib. h> for std input/output Conversion number-text vise-versa, memory allocation, random numbers #include <string. h> string processing 10

Data Types §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 11

Data Types & Memory Allocation Type Bits Bytes Range Char or Signed Char 8 1 -128 to +127 Unsigned Char 8 1 0 to +255 Int or Signed int 32 4 -2, 147, 483, 648 to +2, 147, 483, 647 Unsigned int 32 4 0 to +4, 294, 967, 295 Short int or Signed short int 16 2 -32, 768 to + +32, 767 Unsigned short int 16 2 0 to +65, 535 Long int or signed long int 32 4 -2, 147, 483, 648 to +2, 147, 483, 647 Unsigned long int 32 4 0 to +4, 294, 967, 295 Float 32 4 3. 4 e-38 to 3. 4 e+38 Double 64 8 1. 7 e-308 to 1. 7 e+308 Long Double 64 8 1. 7 e-308 to 1. 7 e+308 12

Variables Naming Conventions §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 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 13

Naming Variables According to Standards Prefix Data Type Example i int and unsigned int i. Total. Score f float f. Average. Score d double d. Height l long and unsigned long l. Factorial c signed char and unsigned char c. Product. Code ai Array of integer ai. Student. Id af Array of float af. Weight ad Array of double ad. Amount al Array of long integer al. Sample ac Array of characters ac. Material 14

Data Types Declaration float f. Income; float income, net_income; float f. Net_income; double d. Base, d. Height, d. Area; Declare and initialize int i. Index =0, i. Count =0; char c. Ch=‘a’, c. Ch 2; const float f. Epf = 0. 1, f. Tax = 0. 05; Named constant declared and initialized 15

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

Arithmetic Operators Used to execute mathematical equations The result is usually assigned to a data storage (instance/variable) using assignment operator ( = ) E. g. sum = marks 1 + marks 2; 17

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

Exercise on Arithmetic Operators Given x = 20, y = 3 z=x%y = 20 % 3 = 2 (remainder) 19

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

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

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

Truth Table for && (logical AND) Operator exp 1 exp 2 exp 1 && exp 2 false false true true 23

Truth Table for || (logical OR) Operator exp 1 exp 2 exp 1 || exp 2 false true false true 24

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

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

Comparison of Prefix and Postfix Increments

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

Operator Precedence Operators Precedence ! + - (unary operators) first * / % second + - (binary operators) third < <= >= > fourth == != fifth && sixth || seventh = last 29

Formatted Output with “printf” #include <stdio. h> void main (void) Declaring variable (f. Month) to be integer { int i. Month; float f. Expense, f. Income; i. Month = 12; Declaring variables (f. Expense and f. Income) to be real f. Expense = 111. 1; Assignment statements store numerical values in the memory cells for the declared variables f. Income = 1000. 0; ‘, ’ separates string literal from variable names printf (“Month=%2 d, Expense=$%9. 2 fn”, i. Month, f. Expense); } Correspondence between variable names and %. . . in string literal 30

Formatted Output with printfcont 31

Formatted input with scanf 32

Formatted input with scanfcont 33

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

Program debugging-syntax error snapshot 35

Program debugging-run time error snapshot 36

Program debugging-logic error snapshot 37

End Week 1 – Session 2 Q & A! 38