Download presentation
Presentation is loading. Please wait.
Published byBruno Franklin Modified over 9 years ago
1
Lecture 2
2
Outline Sample programming question Sample C program Identifiers and reserve words Program comments Preprocessor directives Data types and type declarations Operators Formatted input and output Program debugging
3
Sample Programming Question Write a program that calculate nett income.Your program should read income from user. Given tax rate is 10% and epf rate is 5% from income. 3 Steps: Analyze the problem Use algorithm Convert to actual codes
4
Sample C Program //Program name : program1.c //Programmer : John //This program reads income and calculate nett income //after epf and tax deduction #include int main(void) { float income, net_income; const float epf=0.1, tax=0.05; printf(“Enter income : “); scanf(“%f”, &income); net_income=income-(epf*income) – (tax*income); printf(“\nNett income : %5.2f”, net_income); return 0; } The terms void indicates we receive nothing from OS and return an integer to OS Variable & constant declaration begin end Return 0(int) to OS body Comments Preprocessor directives
5
Identifiers & Reserve Words Identifiers labels for program elements case sensitive can consists 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 Reserve words cannot be identifiers Reserve words already assigned to a pre-defined meaning eg: delete, int, main, include, double, for, if etc.
6
Program comments Starts with /* and terminate with */ OR Character // start a line comment, if several lines, each line must begin with // Comments cannot be nested /* /* */*/
7
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
8
Data Types & Mem. Alloc. Data TypeDescription Size (bytes) char A single character. Internally stored as a coded integer value (refer to ASCII table ). 1 int Integer quantity. Can be represented in signed or unsigned form (with the unsigned keyword). 2 float Floating-point number. Set of real numbers.4 double A more precise version of float. Has larger dynamic range and better representation of decimal points. 8 bool Boolean representation of logic states. Can only be assigned true (1) or false (0). 1
9
Type declarations float income; float net_income; int index =0, count =0; char ch=‘a’, ch2; const float epf = 0.1, tax = 0.05; float income, net_income; Declare and initialize Named constant declared and initialized
10
Exercises: Write a single C statement for the following: 1.Define the variable c, thisVariable, q76345 and num to be of data type int
11
Types of operators Types of operators are: Arithmetic operators (+, -, *, /, %) Relational/Equality operators (>, =, <=, !=) Logical operators (&&, ||) Compound assignment operator (+=, -=, *=, /=, %=) Binary operators: needs two operands Unary operators: single operand Bitwise operators: executes on bit level
12
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;
13
Arithmetic Operators C OperationArithmetic Operator Algebraic expression C expression Addition + f + 7 Subtraction - p – c p - c Multiplication * bm b * m Division / x / y Remainder (Modulus) % r mod s r % s
14
Exercise on arithmetic operators Given x = 20, y = 3 z = x % y = 20 % 3 = 2 (remainder) Order of Precedence a = 5 + 7 % 2 Which one do you want? a = 5 + (7 % 2) // with a result of 6 or a = (5 + 7) % 2 // with a result of 0
15
From high priority to low priority the order for all C operators is:
16
Operator Precedence OperatorsPrecedence ! + -first * / %second + -third = >fourth == !=fifth &&sixth ||seventh =last
17
Example What is the value of A at the end of the program? A, B;
18
Relational and Equality Operators Relational/ Equality operator: >, =, <=, ==, != The result of a relational operation is a Boolean value that can only be true or false,
19
Examples of Relational operators application Relational operators use mathematical comparison (operation) on two data, but gives logical output Examples: if (num1==num2) printf(“num1 is equal to num2”); if (num1!=num2) printf(“num1 is not equal to num2”); if (num1<num2) printf(“num1 is less than num2”); if (num1>=num2) printf(“num1 is greater than or equal to num2”); Reminder: Don’t confuse == (equality op.) with = (assignment op.)
20
Logical Operators Logical operators: !, &&, || && for logical AND, || for logical OR Truth table is given here
21
More on logical operators Examples: if (gender == female && age >= 65) printf(“Increase the number of senior female by one”); if (Coursework >= 90 || FinalExam >=90) printf(“Student grade is A”); if (! (gender == female)) printf(“This person is a male”);
22
Truth table for && (logical AND) operator exp1exp2exp1 && exp2 false truefalse truefalse true
23
Truth table for || (logical OR) operator exp1exp2exp1 || exp2 false true falsetrue
24
Compound assignment operator To calculate value from expression and store it in variable, we use assignment operator (=) Compound assignment operator combine binary operator with assignment operator E.g. c +=3; is equivalent to c = c + 3; E.g. count = count -1; is equivalent to count -=1; count--; --count; E.g. A = 5; or B = 19; A = B; What is the value of A now? E.g. e = 4; e *= 5 What is the value of e now?
25
Unary Operators Obviously operating on ONE operand Increment/decrement { ++, -- } Increment/decrement can be either a prefix or postfix Prefix My_var = 10; A = --My_var; Postfix My_var = 10; A = My_var--;
26
Unary Operators (Eg.) Increment/decrement { ++, -- } prefix:value incr/decr before used in expression postfix:value incr/decr after used in expression val=5; printf(“%d”, ++val); Output: 6 val=5; printf(“%d”, --val); Output: 4 val=5; printf(“%d”, val++); Output: 5 val=5; printf(“%d”, val--); Output: 5
27
Exercises: 1. Assign the sum of x and y to z and increment the value of x by 1 after the summation 2. Decrement the variable x by 1, then subtract it from the variable, total 3. Add the variable, x to the variable, total, then decrement x by 1.
28
Formatted Output with printf
29
Formatted Output with printf- cont
30
Formatted input with scanf
31
Formatted input with scanf- cont
32
Exercises: 1. Print the value of 123.4567 with two digits of precision. What is the value being printed? 2. Print the floating-point value of 3.14159 with three digits to the right of decimal point. What is the value being printed?
33
Exercises: Write a single C statement for the following: 1.Prompt user to enter an integer 2.Read an integer from keyboard and store the value in variable, a 3.If number is not equal to 8, print “The variable number is not equal to 8.” 4.Read three integers from keyboard and store them in variable x,y,z
34
Exercises: cont… 5. Write a complete program that calculates the product of three integers (x,y,z) 6. Identify any error/errors and correct it/them a.scanf (“d”, value) b.Num1 + Num2 = sumNumber c.if (number > = largest) largest = = number; 7. Write a program to ask user to enter two numbers, use the two numbers to print sum, product, difference, quotient, remainder
35
Program debugging Syntax error Mistakes caused by violating “grammar” of C C compiler can easily diagnose during compilation Run-time error 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
36
Program debugging-syntax error snapshot
37
Program debugging-run time error snapshot
38
Program debugging-logic error snapshot
39
End Lecture 2 Q & A!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.