Download Week 3 - Portal UniMAP

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

C Sharp (programming language) wikipedia , lookup

Computer cluster wikipedia , lookup

Programming language wikipedia , lookup

Stream processing wikipedia , lookup

Algorithm wikipedia , lookup

Falcon (programming language) wikipedia , lookup

Object-oriented programming wikipedia , lookup

Functional programming wikipedia , lookup

Parallel computing wikipedia , lookup

Abstraction (computer science) wikipedia , lookup

Reactive programming wikipedia , lookup

Structured programming wikipedia , lookup

Transcript
Week 3
C Program Structure &
Operator
(cont’d)
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
1
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, …
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
2
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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
3
C vs. C++: Similarities
•
•
•
•
Built-in data types: int, double, char, etc.
Preprocessor (handles #include, #define, etc.)
Control structures: if, while, do, for, etc.
Operators: + - * / = == != < > += ++ etc.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
4
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
5
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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
6
Exercise
Write the following expressions in C language.
i)
ii)
m=a+b+c+d+e
5
y = mx + b =>> y=m*x+b
iii)
z = pr%q+w/x-y
z=(p*r%q)+(w/x)-y
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
7
Unary and Binary operator
Two Operands
1 +
2
Binary Operator
Sem1-06/07
One Operands
K - -;
Postfix Unary
Operator
EKT120: COMPUTER
PROGRAMMING
One Operands
- - trees;
Prefix Unary
Operator
8
Preincrementing and postincrementing */
#include <stdio.h>
/* 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 */
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
9
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;
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
10
Assignment
Operator
Sample
Expression
Explanation
Assign
+=
c+= 7
c=c+7
10 to c
-=
d-=4
d=d-4
1 to d
*=
e*= 5
e=e*5
20 to e
/=
f /= 3
f=f/3
2 to f
%=
g %= 9
g=g%9
3 to g
Assume int c = 3, d = 5, e=4, f = 6, g = 12
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
11
Simple C Program
#include <stdio.h>
void main(void)
{
printf(“Welcome To KUKUM\n”);
}
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
12
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<stdio.h>
#include<string.h>
#include<math.h>
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
13
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;
char grade;
//examples of input and output statements a = 25; grade = ‘A’;
printf(“a = ”,a) ;
printf(“Enter two integers: ”) ;
printf(“The numbers you entered are %d %d”,a,b);
//Line
//Line
//Line
//Line
//Line
//Line
printf(“Your grade is %c “,grade);
//Line 10
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
1
2
3
4
5
6
14
Formatted Output with printf-cont
Escape
Sequence
Meaning
Result
\a
Alert/ bell
Generates an audible or visible alert
\b
Backspace
Move the current cursor back 1 space on the current
line
\f
Form feed
Move the active position to the initial position at the
start of the logical page.
\n
New Line
Line feed to the initial position of the new line
\t, \v
Horivontal tab,
vertical tab
Move the cursor to the next horizontal tab
Move the cursor to the next vertical tab
\oddd, \xddd
Octal 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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
15
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 ?
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
16
Output
The square root of 10 is 3.16227766
Field width = 20 with 8 decimal point
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
17
Discussion on
Lab Exercise 1 and 2
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
18
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
19
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
20
Review :
6 steps of problem solving
1.
2.
3.
4.
Identify the problem
Understand the problem
Identify alternative
Select the best ways to solve the
problem
5. List of instructions that can solve the
selected solution
6. Evaluate the solution
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
21
Solution
1.
2.
Identify the problem :
- To get a glass of water from the kitchen.
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?)
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
22
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
23
Solution (Cont’d)
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.
5.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
24
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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
25
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
26
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 Data
Required Result
Hours
Pay Rate
Gross Pay
Processing Required
Solution Alternative
Gross Pay = Hours * Pay Rate
1.
2.
Sem1-06/07
Define the hours worked and pay rate
as constant
Define the hours worked and pay rate
as input values
EKT120: COMPUTER
PROGRAMMING
27
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
Sem1-06/07
CALC
2000
EKT120: COMPUTER
PROGRAMMING
PRINT
3000
28
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
Input
All input data
(section 1 of PAC)
Input
Hours Work
Pay rate
Sem1-06/07
Processing
Module Reference
Number
Output
All processing in
steps (section 3 & 4
of PAC)
Module Reference
from structure chart
All output
requirements
(section 1 & 2 from
PAC)
Processing
1. Enter hours work
2. Enter Pay rate
3. Calculate Pay
4. Print Pay
5. End
Module Reference
Number
1000
1000
2000
3000
0000
EKT120: COMPUTER
PROGRAMMING
Output
Gross Pay
29
Solution to Q1
Problem Analysis Chart
Given Data
Required Result
Number
MaxNumber
Processing Required
Solution 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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
30
Structured Chart:
Main:
MaxNumber
0000
Initialization
1000
Sem1-06/07
GetInput
2000
FindMax
Number
3000
EKT120: COMPUTER
PROGRAMMING
PRINT
4000
31
IPO
Input
Module
ReferenceNumber
Processing
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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
0000
1000
2000
3000
Max
0000
4000
0000
32
Start
Flowchart
Max = 0
Count = 1
“Enter A Number”
Get Number
Max = Number
Yes
Number > Max
Yes
If count <=10
Details
End
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
33
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
34
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.
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
35
Solution To Q2
Start
Check
Account
Withdraw
100
•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.
Yes
Balance >500
No
Balance >=
100
Yes
Withdraw
50
No
End
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
36
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.
2.
3.
4.
5.
6.
7.
Sem1-06/07
Subtract Price from 1 ringgit and store in change.
Divide the change by 50 (sen) and store.
Take the remainder and divide by 20 (sen) and store.
Take the remainder and divide by 10 (sen) and store.
Take the remainder and divide by 5 (sen) and store.
Take the remainder and divide by 1 (sen) and store.
Print out the denominations of the sen.
EKT120: COMPUTER
PROGRAMMING
37
Start
Solution To Q3
Change = 100 - Price
Bil50 = change integer divide 50
Change = Change mod 50
If change = 0
No
Bil20 = change int divide 20
Change = change mod 20
If change = 0
No
Bil10 = change int divide 10
Change = change mod 10
If change = 0
Yes
No
Bil5 = change int divide 5
Change = change mod 5
If change = 0
No
Bil1 = change int divide 1
Change = change mod 1
Display “Change: <Bil50>
50 sen,, <Bil20> 20 sen,
<Bil10> 10 sen, <Bil5> 5
sen and <Bil1> 1 sen”
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
38
End
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
Sem1-06/07
EKT120: COMPUTER
PROGRAMMING
39