Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sem1-06/07EKT120: COMPUTER PROGRAMMING 1 Week 3 C Program Structure & Operator (cont’d)

Similar presentations


Presentation on theme: "Sem1-06/07EKT120: COMPUTER PROGRAMMING 1 Week 3 C Program Structure & Operator (cont’d)"— Presentation transcript:

1 Sem1-06/07EKT120: COMPUTER PROGRAMMING 1 Week 3 C Program Structure & Operator (cont’d)

2 Sem1-06/07EKT120: COMPUTER PROGRAMMING 2 C vs. C++: Differences  C does not have classes/objects!  All code is in functions (subroutines).  C structures can not have methods  C I/O is based on library functions: printf, scanf, fopen, fclose, fread, fwrite, …

3 Sem1-06/07EKT120: COMPUTER PROGRAMMING 3 C vs. C++: Differences  C does not support any function overloading (we can’t have 2 functions with the same name).  C does not have new or delete, malloc() and free() library functions is used to handle  Dynamic memory allocation/deallocation.  C does not have reference variables

4 Sem1-06/07EKT120: COMPUTER PROGRAMMING 4 Built-in data types: int, double, char, etc. Preprocessor (handles #include, #define, etc.) Control structures: if, while, do, for, etc. Operators: + - * / = == != += ++ etc. C vs. C++: Similarities

5 Sem1-06/07EKT120: COMPUTER PROGRAMMING 5 C vs. C++: Similarities (cont.)  There must be a function named main().  function definitions are done the same way.  Can split code in to files (object modules) and link modules together.

6 Sem1-06/07EKT120: COMPUTER PROGRAMMING 6 Types of operators  Types of operators are: Arithmetic operators (+, -, *, /, %) Relational operators (>, =, <=, !=) Logical operators (&&, ||) Compound assignment operator (+=, -=, *=, /=, %=)  Binary operators: needs two operands  Unary operators: single operand  Bitwise operators: executes on bit level

7 Sem1-06/07EKT120: COMPUTER PROGRAMMING 7 Exercise Write the following expressions in C language. i)m = a + b + c + d + e 5 ii)y = mx + b =>> y=m*x+b iii)z = pr%q+w/x-y z=(p*r%q)+(w/x)-y

8 Sem1-06/07EKT120: COMPUTER PROGRAMMING 8 Unary and Binary operator 1+2 Two Operands Binary Operator K- -; Postfix Unary Operator One Operands trees;- Prefix Unary Operator One Operands

9 Sem1-06/07EKT120: COMPUTER PROGRAMMING 9 Preincrementing and postincrementing */ #include /* function main begins program execution */ int main() { int c; /* define variable */ /* demonstrate postincrement */ c = 5; /* assign 5 to c */ printf( "%d\n", c ); /* print 5 */ printf( "%d\n", c++ ); /* print 5 then postincrement */ printf( "%d\n\n", c ); /* print 6 */ /* demonstrate preincrement */ c = 5; /* assign 5 to c */ printf( "%d\n", c ); /* print 5 */ printf( "%d\n", ++c ); /* preincrement then print 6 */ printf( "%d\n", c ); /* print 6 */ return 0; /* indicate program ended successfully */ } /* end function main */

10 Sem1-06/07EKT120: COMPUTER PROGRAMMING 10 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. val +=one; is equivalent to val = val + one; E.g. count = count -1; is equivalent to count -=1; count--; --count;

11 Sem1-06/07EKT120: COMPUTER PROGRAMMING 11 Assignment Operator Sample Expression ExplanationAssign +=c+= 7c = c + 710 to c -=d-=4d = d - 41 to d *=e*= 5e = e * 520 to e /=f /= 3f = f / 32 to f %=g %= 9g = g % 93 to g Assume int c = 3, d = 5, e=4, f = 6, g = 12

12 Sem1-06/07EKT120: COMPUTER PROGRAMMING 12 Simple C Program #include void main(void) { printf(“Welcome To KUKUM\n”); }

13 Sem1-06/07EKT120: COMPUTER PROGRAMMING 13 C Libraries  Standard I/O: printf, scanf, fopen, fread, …  String functions: strcpy, strspn, strtok, …  Math: sin, cos, sqrt, exp, abs, pow, log,… And many more….refer Deitel page 154 #include

14 Sem1-06/07EKT120: COMPUTER PROGRAMMING 14 Formatted Output with printf  To display result of the program can be done by using keyword printf and operator as shown below: printf(“formating”,variable) ; //this is variable declaration int a, b;//Line 1 char grade;//Line 2 //examples of input and output statements a = 25; grade = ‘A’;//Line 3 printf(“a = ”,a) ; //Line 4 printf(“Enter two integers: ”) ;//Line 5 printf(“The numbers you entered are %d %d”,a,b);//Line 6 printf(“Your grade is %c “,grade); //Line 10

15 Sem1-06/07EKT120: COMPUTER PROGRAMMING 15 Formatted Output with printf-cont Escape Sequence MeaningResult \aAlert/ bellGenerates an audible or visible alert \bBackspaceMove the current cursor back 1 space on the current line \fForm feedMove the active position to the initial position at the start of the logical page. \nNew LineLine feed to the initial position of the new line \t, \vHorivontal tab, vertical tab Move the cursor to the next horizontal tab Move the cursor to the next vertical tab \oddd, \xdddOctal constant Hexal constant Represent an integer to base 8 number Represent an integer to base 16 number \\, \’, \?, \”Backslash, single quote, Q mark, double quote Tp show backslash, single quote, question mark and double quote \%, \%d, \%f, Percent, format decimal number, float number To show symbol %, and format number d is integer number, f – float number

16 Sem1-06/07EKT120: COMPUTER PROGRAMMING 16 printf Let the square root of 10 is 3.162277660168380 printf(“The square root of 10 is %20.8f\n”,sqrt(10)); What is the output ?

17 Sem1-06/07EKT120: COMPUTER PROGRAMMING 17 The square root of 10 is 3.16227766 Output Field width = 20 with 8 decimal point

18 Sem1-06/07EKT120: COMPUTER PROGRAMMING 18 Discussion on Lab Exercise 1 and 2

19 Sem1-06/07EKT120: COMPUTER PROGRAMMING 19 Exercise 1  Choose one of the tasks below and write a set of numbered, step by step instructions that a person can do it without asking questions. List the knowledge base of this person (What do you expect the person should know to perform the task).  Make a cup of coffee  Sharpen a pencil  Get a glass of water from your kitchen.

20 Sem1-06/07EKT120: COMPUTER PROGRAMMING 20 Review: Problem Solving Concept For Computer  Problem that can be solve with computers generally consist of three: Computational – problem with mathematical processing Logical – problem involving with relational or logical processing. This is kind of processing involve in decision making. Repetitive – problem involving repeating a set of mathematical or logical instructions.

21 Sem1-06/07EKT120: COMPUTER PROGRAMMING 21 Review : 6 steps of problem solving 1. Identify the problem 2. Understand the problem 3. Identify alternative 4. Select the best ways to solve the problem 5. List of instructions that can solve the selected solution 6. Evaluate the solution

22 Sem1-06/07EKT120: COMPUTER PROGRAMMING 22 Solution 1.Identify the problem : - To get a glass of water from the kitchen. 2.Understand the problem : - Knowledgebase of a person The person know where the kitchen? (The person might be our guest). The person need to know where our water. (In the fridge? So need to know where the fridge is) Where the glass is? (From the cupboard?)

23 Sem1-06/07EKT120: COMPUTER PROGRAMMING 23 Solution (Cont’d) 3. Identify alternative :  Is there any other way to the kitchen?  Can get a glass of water from the dining room.  Prefer cold water or normal water or warm water.  Can get glass from the rack. 4.Select the best ways to solve the problem : Get cold plain water from the fridge in the kitchen and can get glass from the rack near the sink.

24 Sem1-06/07EKT120: COMPUTER PROGRAMMING 24 Solution (Cont’d) 5. List of instructions that can solve the selected solution: Go to the kitchen. The rack is beside the sink and the sink is at the window. Go to the fridge, the fridge is white color, and it is near the door. Open the fridge. The plain water is in the coca – cola bottle at the bottom rack. 6.Evaluate the solution: Follow the instruction, and is there really a fridge, and is there a plain cold water in the fridge.

25 Sem1-06/07EKT120: COMPUTER PROGRAMMING 25 Exercise 2 Question 1: Write a solution to a problem of finding the largest number out of ten numbers. Present the solution in the problem organizing tools (PAC, Structured Chart, IPO chart). Complete the solution by developing a pseudocode and a flowchart. Test your algorithm with the below data: 33, 10, 40, 30, 22, 29, 50, 69, 40, 67

26 Sem1-06/07EKT120: COMPUTER PROGRAMMING 26 Review: Organizing The Problem  There are several organizational tool can be used in problem solving Problem Analysis Chart – the beginning analysis of the problem Structured Chart – shows the overall layout or structure of the solution IPO Chart – shows the input, the processing and the output  Algorithm is the sequence of instructions comprising the solution  Flowcharts is the graphic representations of the algorithm.

27 Sem1-06/07EKT120: COMPUTER PROGRAMMING 27 Problem Analysis Chart (PAC)  Consist of 4 separate parts Section 1 - The given data – Data given or provided by user, can be known value or general name. Section 2 - The required result – Requirement for the output report, information needed and the format required. Section 3 - The processing – List of processing required, include equation or other type of processing, sort, searching and so forth. Section 4 - A list of solution – List of ideas for solution of the problem. Let consider Payroll problem calculating Gross Pay of a worker end of the day. Given DataRequired Result Hours Pay Rate Gross Pay Processing RequiredSolution Alternative Gross Pay = Hours * Pay Rate 1.Define the hours worked and pay rate as constant 2.Define the hours worked and pay rate as input values

28 Sem1-06/07EKT120: COMPUTER PROGRAMMING 28 Structured Chart  Divide the problem into subtasks called modules or smaller subtasks.  This breakdown enable you to view complex problems. It only shows you what will happen and not how its happen.  Use Top-Down Solution method Main: PAYROLL 0000 READ 1000 CALC 2000 PRINT 3000

29 Sem1-06/07EKT120: COMPUTER PROGRAMMING 29 IPO (Input-Processing-Output) Chart  IPO Extends and organizes the information in the problem analysis chart.  Shows more detail what data items are inputs what processing takes place on the data, and what InputProcessingModule Reference Number Output All input data (section 1 of PAC) All processing in steps (section 3 & 4 of PAC) Module Reference from structure chart All output requirements (section 1 & 2 from PAC) InputProcessingModule Reference Number Output Hours Work Pay rate 1. Enter hours work 2. Enter Pay rate 3. Calculate Pay 4. Print Pay 5. End 1000 2000 3000 0000 Gross Pay

30 Sem1-06/07EKT120: COMPUTER PROGRAMMING 30 Solution to Q1 Problem Analysis Chart Given DataRequired Result Number MaxNumber Processing RequiredSolution Alternative 1.Initialize Max = 0 2.if Number > then 3. Max = Number 4.if count < = 10 5. Get Next Number 6.else 7. MaxNumber = Max 1.Define the Number as integer 2.Or define number as real 3.Define the count as integer 4.Get Input from fail 5.Get input from keyboard 6.Print Message to input a number

31 Sem1-06/07EKT120: COMPUTER PROGRAMMING 31 Structured Chart: Main: MaxNumber 0000 Initialization 1000 GetInput 2000 FindMax Number 3000 PRINT 4000

32 Sem1-06/07EKT120: COMPUTER PROGRAMMING 32 IPO InputProcessingModule ReferenceNumber Output Number 1.Start 2.Initialize Max = 0, count = 1 3.Get Number 4.if Number > then 5. Max = Number 6.end if 7.if count < = 10 8. Get Number 9. Repeat step 3 10.End if 11.Print Max 12.End 0000 1000 2000 3000 0000 4000 0000 Max

33 Sem1-06/07EKT120: COMPUTER PROGRAMMING 33 Flowchart Details

34 Sem1-06/07EKT120: COMPUTER PROGRAMMING 34 Exercise 2 : Q2 Karim wants to get some money from his bank account via the ATM. Karim do not know his account balance and needs to check it first before deciding what is the amount that he wants to withdraw. If the balance is over RM500, he will withdraw RM100; otherwise he will withdraw a mere RM50. However if the balance is below RM 100 he will not proceed with his intentions. Write an algorithm and draw a flow chart to show this problem. Check the ATM account Decide the account balance If Less than RM 100 terminate. If More than RM 500 withdraw RM 100 then terminate Else Withdraw RM 50 Terminate.

35 Sem1-06/07EKT120: COMPUTER PROGRAMMING 35 Review: Algorithms  Organizing the solution where programmer develop a set of instruction for the computer and this is call algorithm.  Pseudo code may be use, it is close to the actual programming language that the programmer will used later.  To complete it, the programmer will write another separate set of instruction (coding/program) that will be understand by the computer.  Instead of Pseudo code, we can also represent the set of instruction in term of Flowchart ( a graphical presentation of the algorithm.

36 Sem1-06/07EKT120: COMPUTER PROGRAMMING 36 Solution To Q2 Check the ATM account Decide the account balance If Less than RM 100 terminate. If More than RM 500 withdraw RM 100 then terminate Else Withdraw RM 50 Terminate.

37 Sem1-06/07EKT120: COMPUTER PROGRAMMING 37 Exercise 2 : Q3 Your need to pay for some purchase with a one ringgit bill and get change in sen. Write the algorithm and draw the flow chart to determine the correct change with the fewest 1 sen. Assume that you need to pay 64 sen and need change for one ringgit. (Hint: use all current coin denominations in the Malaysian currency system.) 1.Subtract Price from 1 ringgit and store in change. 2.Divide the change by 50 (sen) and store. 3.Take the remainder and divide by 20 (sen) and store. 4.Take the remainder and divide by 10 (sen) and store. 5.Take the remainder and divide by 5 (sen) and store. 6.Take the remainder and divide by 1 (sen) and store. 7.Print out the denominations of the sen.

38 Sem1-06/07EKT120: COMPUTER PROGRAMMING 38 Solution To Q3

39 Sem1-06/07EKT120: COMPUTER PROGRAMMING 39 Conclusion Modules in C are called functions. Functions - Library functions - User-Defined functions Library functions – modules that already have been developed, included in C compiler. User-defined function – made by programmer Comments Preprocessor directives Algorithmic solution, Heuristic solution 6 steps in problem solving Problem organizational tool (PAC, Structured Chart, IPO) Algorithm, pseudo code, flowchart Operators in C C program structure


Download ppt "Sem1-06/07EKT120: COMPUTER PROGRAMMING 1 Week 3 C Program Structure & Operator (cont’d)"

Similar presentations


Ads by Google