Morteza Noferesti Concept of algorithms Understand and use three - - PowerPoint PPT Presentation
Morteza Noferesti Concept of algorithms Understand and use three - - PowerPoint PPT Presentation
Morteza Noferesti Concept of algorithms Understand and use three tools to represent algorithms: Flowchart Pseudocode Programs We want to solve a real problem by computers Take average, Sort, Painting, Web, Multimedia,..
Concept of algorithms Understand and use three tools to represent algorithms:
- Flowchart
- Pseudocode
- Programs
We want to solve a real problem by computers
- Take average, Sort, Painting, Web, Multimedia,..
We need a solution that
- Specifies how the real (complex) problem should be solved step-
by-step using the basic operations
The solution is the Algorithm of the problem Characteristics
- Specific
- Unambiguous
- Language independent
Algorithms are the problem solving steps/strategy in our
mind!!!
How can we document it (don’t forget it)? How can explain/teach it to others peoples? How can explain it to computers? We need some methods to describe algorithms!
- Flow chart
- Pseudo-codes
- Codes/Programs
A typical programming task can be divided into two
phases:
Problem solving phase
- produce an ordered sequence of steps that describe solution
- f problem
- this sequence of steps is called an algorithm
Implementation phase
- implement the program in some programming language
First produce a general algorithm (one can use
pseudo code)
Refine the algorithm successively to get step by step
detailed algorithm that is very close to a computer language.
Pseudo code is an artificial and informal language
that helps programmers develop algorithms. Pseudo code is very similar to everyday English.
Employs 'programming-like' statements to depict the
algorithm
No standard format (language independent)
Write an algorithm to determine a student’s final
grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.
Input a set of 4 marks Calculate their average by summing and dividing by 4 if average is below 50
Print “FAIL” else Print “PASS”
Step 1: Input M1,M2,M3,M4
Step 2: GRADE M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then Print “FAIL” else Print “PASS” endif
A graphical representation of the sequence of
- perations in an information system or program.
A Flowchart
- shows logic of an algorithm
- emphasizes individual steps and their interconnections
- e.g. control flow from one action to the next
Oval Parallelogram Rectangle Diamond Hybrid Name Symbol Use in Flowchart Denotes the beginning or end of the program Denotes an input operation Denotes an output operation Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE) Denotes a process to be carried out e.g. addition, subtraction, division etc. Flow line Denotes the direction of logic flow in the program
PRINT NT “PASS”
Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then Print “FAIL” else Print “PASS” endif
START Input M1,M ,M2,M ,M3,M ,M4 GRADE(M (M1+M +M2+M +M3+M +M4)/ )/4 IS IS GRADE<50 50 PRINT “FAIL” STOP Y N
Write an algorithm and draw a flowchart to convert the
length in feet to centimeter.
Pseu eudo do code:
Input the length in feet (Lft) Calculate the length in cm (Lcm) by multiplying LFT with 30 Print length in cm (LCM)
Algorithm
Step 1: Input Lft Step 2:
Lcm Lft x 30
Step 3:
Print Lcm
START
Input Lft Lcm Lft x 30
Print Lcm
STOP
Flowchart
A flowchart for the
pay-calculating program
START
Display message “How many hours did you work?” Read Hours Display message “How much do you get paid per hour?” Read Pay Rate
Multiply Hours by Pay
- Rate. Store result in
Gross Pay.
Display Gross Pay
END
Write an algorithm and draw a flowchart that will
read the two sides of a rectangle and calculate its area. Pseudo code Input the width (W) and Length (L) of a rectangle Calculate the area (A) by multiplying L with W Print A
Algorithm
Step 1:
Input W,L
Step 2:
A L * W
Step 3:
Print A
START Input W, L A L * W Print A STOP
Write an algorithm and draw a flowchart that will
calculate the roots of a quadratic equation
Hint: d = sqrt ( ), and the roots are:
x1 = (–b + d)/2a and x2 = (–b – d)/2a
2
ax bx c
2
4 b ac
Pseud eudo code:
Input the coefficients (a, b, c) of the quadratic equation Calculate d Calculate x1 Calculate x2 Print x1 and x2
Algorithm:
Step 1:
Input a, b, c
Step 2:
d sqrt ( )
Step 3:
x1 (–b + d) / (2 x a)
Step 4:
x2 (–b – d) / (2 x a)
Step 5:
Print x1, x2
START Input a, b, c d sqrt(b x b – 4 x a x c) Print x1 ,x2 STOP x1 (–b + d) / (2 x a) X2 (–b – d) / (2 x a)
4 b b a c
The structure is as follows
If condition then true alternative//S1 else false alternative//S2 endif
condition S2 S1 Y N
The expression A>B is a logical expression if A>B is true (if A is greater than B) we take the
action on left
- print the value of A
if A>B is false (if A is not greater than B) we take the
action on right
- print the value of B
is A>B Print B Print A Y N
Conditions by comparisons; e.g.,
- If a is greater then b
- If c equals to d
Comparing numbers: Relational Operators
Relations produce a boolean value
int a, b; bool bl; // #include <stdbool.h> bl = a == b; bl = a <= b;
C Boolean operators
and &&
- r
|| not !
p q p && q p || q !p False False False False True False True False True True True False False True False True True True True False
Examples
bool a = true, b=false, c; c = !a;
//c=false
c = a && b;
//c=false
c = a || b;
//c=true
c = !a || b;
//c=false
Write an algorithm that reads two values, determines the
largest value and prints the largest value with an identifying message. ALGORITHM
Step 1: Input VALUE1, VALUE2 Step 2: if (VALUE1 > VALUE2) then MAX VALUE1 else MAX VALUE2 endif Step 3: Print “The largest value is”, MAX
MAX VALUE1 Print “The largest value is”, MAX STOP Y N START Input VALUE1,VALUE2 MAX VALUE2
is VALUE1>VALUE2
Display “x is within limits.” Display “x is outside the limits.”
YES NO
x > min? x < max?
YES NO
Display “x is outside the limits.”
if (x > min) { if (x < max) printf("x is within the limits"); else printf("x is outside the limits"); } else printf("x is outside the limits");
Write and algorithm to
a)
read an employee name (NAME), overtime hours worked (OVERTIME), hours absent (ABSENT) and
b)
determine the bonus payment (PAYMENT).
Bonus Schedule OVERTIME – (2/3)*ABSENT Bonus Paid >40 hours >30 but 40 hours >20 but 30 hours >10 but 20 hours 10 hours $50 $40 $30 $20 $10
Step 1: Input NAME,OVERTIME,ABSENT Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then PAYMENT 50 else if (OVERTIME–(2/3)*ABSENT > 30) then PAYMENT 40 else if (OVERTIME–(2/3)*ABSENT > 20) then PAYMENT 30 else if (OVERTIME–(2/3)*ABSENT > 10) then PAYMENT 20 else PAYMENT 10 endif Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
Algorithm: calculate 12 + 22 + ⋯ + 𝑜2 Input: n
Output: sum sum ← 0 i ← 1 Repeat the following three steps while i ≤ n: sq ← i * i sum ← sum + sq i ← i + 1
The flowchart reads three numbers and prints the value
- f the largest number.
Step 1: Input N1, N2, N3 Step 2: if (N1>N2) then if (N1>N3) then MAX N1 [N1>N2, N1>N3] else MAX N3 [N3>N1>N2] endif else if (N2>N3) then MAX N2 [N2>N1, N2>N3] else MAX N3 [N3>N2>N1] endif endif Step 3: Print “The largest number is”, MAX
#include <stdio.h> int main(void){ int number_to_test, remainder; printf("Enter your number to be tested: "); scanf("%d", &number_to_test); remainder = number_to_test % 2; if(remainder == 0) printf ("The number is even.\n”) else printf ("The number is odd.\n”) return 0; }
Assign value according to conditions A ternary operator
int i, j, k; bool b; ... i = b ? j : k; /*if(b) * i=j * else * i=k; */
y = abs(x)
y = (x > 0) ? x : -x;
signum = (x < 0) ? -1 : (x > 0 ? 1 : 0)
int d = numg / 25; charg =
(d == 0) ? ‘D’ : ((d == 1) ? ‘C’ : (d == 2) ? ‘B’ : ‘A’);
Danger of assignment (=) and equality (==)
int a = 10; int b = 20; if(a=b) // Logical Error
Danger of similarity between C and mathematic
- if(a < b < c)
- if(a && b > 0)
// Logical // Logical Error Error
; is a null statement!
#include <stdio.h> int main() { int num; printf("enter a number>>"); scanf("%d",&num); if (num>100);
printf("This statement always is displayed!");
return 0; }
Multiple conditions
- If-else if-else if-….
Select from alternative values of a variable
- switch-case
- Values should be constant not expression: i,
- Values & Variables should be int or char
Each switch-case can be rewritten by If-else
- if-else version of switch-case in the previous slide
if(variable == value1)} <statements 1> <statements 2> } else if(variable == value2){ <statements 2> }
If(variable == value1) { <statements 1> } else if(variable == value2) { <statements 2> } else{ <statements 3> } switch(variable){ case value1: <statements 1> break; case value2: <statements 2> break; default: <statements 3> }
Get the operation (contains +,-,*,/,\) as a character
(variable name: op)!
Get two input numbers (variable names: num1, num2 ). Compute and display the expression of:
num1 (op) num2
+
- *
/or\
Header file: <ctype.
ype.h>
Function Work Of Function isalnum Tests whether a character is alphanumeric or not isalpha Tests whether a character is aplhabetic or not iscntrl Tests whether a character is control or not isdigit Tests whether a character is digit or not isgraph Tests whether a character is grahic or not islower Tests whether a character is lowercase or not isprint Tests whether a character is printable or not ispunct Tests whether a character is punctuation or not isspace Tests whether a character is white space or not isupper Tests whether a character is uppercase or not isxdigit Tests whether a character is hexadecimal or not tolower Converts to lowercase if the character is in uppercase toupper Converts to uppercase if the character is in lowercase
switch(opr){ case '+': res = opd1 + opd2; break; case '-': res = opd1 - opd2; break; case '/': res = opd1 / opd2; break; #include <stdio.h> #include <stdlib.h> int main(void){ int res, opd1, opd2; char opr; printf("Operand1 : "); scanf("%d", &opd1); printf("Operand2 : "); scanf("%d", &opd2); printf("Operator : "); scanf(" %c", &opr);
case '*': res = opd1 * opd2; break; default: printf("Invalid operator \n"); return -1; } printf("%d %c %d = %d\n", opd1, opr, opd2, res); return 0; }
switch(variable){ case case value1: value2: <statements 1> break; case value3: <statements 2> }
If( (variable == value1) || (variable == value2) ){ <statements 1> == value3) } else if (variable { <statements 2> }
if-else is more powerful than switch-case
- switch-case is only for checking the values of a
variable and the values must be constant
Some if-else cannot be rewritten by switch-case
double var1, var2; if(var1 <= 1.1) <statements 1> if(var1 == var2) <statements 2>
bool b; //b = x && y switch (x){ case 0: b = 0; break; case 1: switch(y){ case case 0: b = 0; break; 1: b = 1; break; } break; }
All values used in case should be different
switch(i){ //Error case 1: … case 2: … case 1: …
All values must be value, not expression of variables
switch(i){ //Error case j: … case 2: … case k+10: …
While Do while For
- Example: Write a program that read 3 integer and
compute average
- It is easy. 3 scanf, an addition, a division and, a printf
- Example: Write a program that read 3000 integer
and compute average
- ?? 3000 scanf !!!
- Example: Write a program that read n integer and
compute average
- N??? scanf
- Repetition in algorithms
- A loop is a group of instructions the computer executes
repeatedly while some loop-continuation condition remains true.
- We have discussed two means of repetition:
- Counter-controlled repetition
- Sentinel-controlled repetition
- Counter-controlled repetition is sometimes called definite
repetition because we know in advance exactly how many times the loop will be executed.
- Sentinel-controlled repetition is sometimes called indefinite
repetition because it’s not known in advance how many times the loop will be executed.
- In counter-controlled repetition, a control variable is used
to count the number of repetitions.
- Counter-controlled repetition requires:
- The initial value of the control variable.
- The increment (or decrement) by which the control variable is
modified each time through the loop.
- The condition that tests for the final value of the control variable
(i.e., whether looping should continue).
- When we know the number of iteration
- Average of 10 number
Initialize counter = 0 Initialize other variables While (counter < number of loop repetition) do something (e.g. read input, take sum) counter = counter + 1
- Consider the following problem statement:
A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.
- Sentinel values are used to control repetition when:
- The precise number of repetitions is not known in advance, and
- The loop includes statements that obtain data each time the loop
is performed.
- The sentinel is entered after all regular data items have
been supplied to the program.
- Sentinels must be distinct from regular data items.
- When we do NOT know the number of iteration
- But we know, when loop terminates
- E.g. Average of arbitrary positive numbers ending with <0
Get first input as n While (n is not sentinel) do something (sum, …) get the next input as n if (there is not any valid input) then S1 else S2
- Consider the following problem:
- Develop a class averaging program that will process
an arbitrary number of grades each time the program is run.
- One way to solve this problem is to use a special value
called a sentinel value (also called a signal value, a dummy value, or a flag value) to indicate “end of data entry.”
- The user types in grades until all legitimate grades
have been entered.
- The user then types the sentinel value to indicate that
the last grade has been entered.
- Clearly, the sentinel value must be chosen so that it
cannot be confused with an acceptable input value.
- Repetition is performed by loops
- Put all statements to repeat in a loop
- Don’t loop to infinity
- Stop the repetition
- Based on some conditions (counter, sentinel)
- C has 3 statements for loops
- while statement
- do-while statement
- for statement
- A loop tests a condition, and if the condition
exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists
x < y? Process A YES
while ( <expression> ) <statements>
ددع هک دیسیونب یا همانرب n ربراک زا ار دادعا و دریگب0 ات nدنک پاچ ار.
<stdio.h> int main(void){ int n, number; number = 0; printf("Enter n: "); scanf("%d", &n); while(number <= n){ number); printf("%d \n", number++; } return 0; }
#include <stdio.h> int main(void){ int negative_num, positive_num; int number; negative_num = positive_num = 0; printf("Enter Zero to stop \n"); printf("Enter next number: "); scanf("%d", &number); while(number != 0){ if(number > 0) positive_num++; else negative_num++; printf("Enter next number: "); scanf("%d", &number); = %d\n", positive_num); = %d\n", negative_num); } printf("The number of positive numbers printf("The number of negative numbers return 0; }
Consider a program segment designed to find the first power
- f 3 larger than 100.
When the following while repetition statement finishes
executing, product will contain the desired answer:
product = 3; while while ( product <= ( product <= 100 ) { ) { product = product = 3 * product; } /* end while */ /* end while */
do <statements> while (<expression>);
#include <stdio.h> int main(void){ int n; double number, sum; printf("Enter n > 0: "); scanf("%d", &n);
- 1;}
if(n < 1){printf("wrong input"); return sum = 0; number = 0.0; do{ number++; sum += number / (number + 1.0); }while(number < n); printf("sum = %f\n", sum); return 0; }
#include <stdio.h> int main(void){ int negative_num=0, positive_num=0; int number; printf("Enter Zero to stop \n"); do{ printf("Enter next number: "); scanf("%d", &number); if(number > 0) positive_num++; else if(number < 0) negative_num++; }while(number != 0); numbers numbers = %d\n", positive_num); = %d\n", negative_num); printf("The number of positive printf("The number of negative return 0; }
for(<expression1>;<expression2>; <expression3>) <statements>
int x, sum, i; sum = 0; for (i = 1; i < 6; i++) { scanf(“%d”,&x); sum = sum + x; } printf(“%d”,sum);
counter ← 1, sum ← 0 counter < 6 sum ← sum + n
false
true counter++
- utput sum
input n
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 1 _
num 1 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 1 1 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 2 1 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 2 1 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 2 1 2 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 3 1 2 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 3 1 2 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 3 1 2 3 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 4 1 2 3 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
num 4 1 2 3 _
Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);
4 1 2 3 have come to exit_
int grade, count, i; double average, sum; sum = 0;
", (i + 1));
printf("Enter the number of students: "); scanf("%d", &count); for(i = 0; i < count; i++){
printf("Enter the grade of %d-th student:
scanf("%d", &grade); sum += grade; } average = sum / count; average); printf("The average of your class is %0.3f\n", return 0; }
int n, number; printf("Enter n: "); scanf("%d", &n); for(number = 1; number if((number % 2) == <= n; number++) 0) printf("%d \n", number); return 0; }
int n, number; printf("Enter n: "); scanf("%d", &n); for(number = 2; number <= n; number += 2) printf("%d \n", number); return 0; }
- The following examples show methods of varying the control
variable in a for statement.
- Vary the control variable from 1 to 100 in increments of 1.
- for
for ( i = ( i = 1; i <= 100 100; i++ )
- Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).
- for
for ( i = ( i = 100 100; i >= 1; i--
- - )
- Vary the control variable from 7 to 77 in steps of 7.
- for
for ( i = ( i = 7; i <= 77 77; i += 7 )
- Vary the control variable from 20 to 2 in steps of -2.
- for
for ( i = ( i = 20 20; i >= 2; i -= = 2 )
- Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.
- for
for ( j = ( j = 2; j <= 17 17; j += 3 )
- Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.
- for
for ( j = ( j = 44 44; j >= 0; j -= = 11 11 )
- Expression1 and Expression3 can be any number of expressions
- for(i = 0, j = 0; i < 10; i++, j--)
- Expression2 at most should be a single expression
- for(i = 0, j = 0; i < 10, j > -100; i++, j--)
//ERROR
- Any expression can be empty expression
- for(;i<10;t++)
- for(;;)//infinite loop
- The three expressions in the for statement are optional.
for(;;)
- One may omit expression1 if the control variable is initialized
elsewhere in the program.
- If expression2 is omitted, C assumes that the condition is true,
thus creating an infinite loop.
- expression3 may be omitted if the increment is calculated by
statements in the body of the for statement or if no increment is needed.
- <statement> in loops can be empty
while(<expression>) ; E.g., while(i++ <= n) ; for(<expression1>; <expression2>;<expression3>); E.g., for(i = 0; i < 10; printf("%d\n",i), i++) ;
- <statement> in loops can be loop itself
while(<expression0>) for(<expression1>; <expression2>;<expression3>) <statements> for(<expression1>; <expression2>;<expression3>) do <statements> while(<expression>);
- A program that takes n and m and prints
*** ….* (m * in each line) *** ….* … *** ….* (n lines)
int main(void){ int i, j, n, m; printf("Enter n & scanf("%d%d", &n, m: "); &m); for(i = 0; i < n; i++){ for(j = 0; j < m; j++) printf("*"); printf("\n"); } return 0; }
- A program that takes n and prints
* ** *** (i * in i-th line) *** ….* (n lines)
#include <stdio.h>
int main(void){ int i, j, n; printf("Enter n: "); scanf("%d", &n); i = 1; while(i <= n){ for(j = 0; j < i; j++) printf("*"); printf("\n"); i++; } return 0; }
- A program that takes a number and generates the following
pattern
Input = 5
* ** *** **** ***** **** *** ** * for(i= 1; i <= n; i++){ for(j= 0; j < i-1;j++) printf(" "); for(j= 1; j <= i; j++) printf("*"); printf("\n"); } for(i=n-1; i >= 1; i--){ for(j= 1; j < i; j++) printf(" "); for(j = 1; j <= i; j++) printf("*"); printf("\n"); }
- The break and continue statements are used to alter the flow
- f control.
- The break statement, when executed in a while, for,
do…while or switch statement, causes an immediate exit from that statement.
- Program execution continues with the next statement.
- Exit from loop based on some conditions
do{ scanf("%d", &a); scanf("%d", &b); if(b == 0) break; res = a / b; printf("a /= %d\n", res); }while(b > 0);
int i,j; for(i=1; i<6;i++){ for(j =1; j<6;j++) { printf("%d %d\n" , i,j); if(j==3) break; } }
int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=sqrt(n); ++i) { if(!n%i) { flag=1; break; } } if (!flag) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n);
- Jump to end of loop and continue repetition
- The continue statement, when executed in a while, for or do…while
statement, skips the remaining statements in the body of that control statement and performs the next iteration of the loop.
do{ scanf("%f", &a); scanf("%f", &b); if(b == 0) continue; res = a / b; printf("a / b= %f\n", res); }while(a> 0);
When you know the number of repetition
- Counter-controlled loops
- Usually, for statements
When you don’t know the number of repetitions (sentinel loop)
- Some condition should be check before starting
loop
- Usually, while statement
- The loop should be executed at least one time
- Usually, do-while statement
- Loop should terminate
- E.g., in for loops, after each iteration, we should approach to the
stop condition
for(i = 0; i < 10; i++) //OK for(i = 0; i < 10; i--) //Bug
- Initialize loop control variables
int i; for( ; i < 10; i++) //Bug
- Don’t modify forloop controller in loop body
for(i = ... i--; 0; i < 10; i++){ //Bug }
- Take care about wrong control conditions
- < vs. <=
- = vs. ==