Morteza Noferesti Concept of algorithms Understand and use three - - PowerPoint PPT Presentation

morteza noferesti concept of algorithms understand and
SMART_READER_LITE
LIVE PREVIEW

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,..


slide-1
SLIDE 1

Morteza Noferesti

slide-2
SLIDE 2

 Concept of algorithms  Understand and use three tools to represent algorithms:

  • Flowchart
  • Pseudocode
  • Programs
slide-3
SLIDE 3

 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
slide-4
SLIDE 4

 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
slide-5
SLIDE 5

 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
slide-6
SLIDE 6

 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.

slide-7
SLIDE 7

 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)

slide-8
SLIDE 8

 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.

slide-9
SLIDE 9

 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”

slide-10
SLIDE 10

 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

slide-11
SLIDE 11

 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
slide-12
SLIDE 12

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

slide-13
SLIDE 13

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

slide-14
SLIDE 14

 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)

slide-15
SLIDE 15

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

slide-16
SLIDE 16

 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

slide-17
SLIDE 17

 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

slide-18
SLIDE 18

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

slide-19
SLIDE 19

 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 

slide-20
SLIDE 20

Pseud eudo code:

Input the coefficients (a, b, c) of the quadratic equation Calculate d Calculate x1 Calculate x2 Print x1 and x2

slide-21
SLIDE 21

 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    

slide-22
SLIDE 22

 The structure is as follows

If condition then true alternative//S1 else false alternative//S2 endif

condition S2 S1 Y N

slide-23
SLIDE 23

 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

slide-24
SLIDE 24

 Conditions by comparisons; e.g.,

  • If a is greater then b
  • If c equals to d

 Comparing numbers: Relational Operators

slide-25
SLIDE 25

 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 !

slide-26
SLIDE 26

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

slide-27
SLIDE 27

 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

slide-28
SLIDE 28

 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

slide-29
SLIDE 29

MAX  VALUE1 Print “The largest value is”, MAX STOP Y N START Input VALUE1,VALUE2 MAX  VALUE2

is VALUE1>VALUE2

slide-30
SLIDE 30

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.”

slide-31
SLIDE 31

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");

slide-32
SLIDE 32

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

slide-33
SLIDE 33

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

slide-34
SLIDE 34

 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

slide-35
SLIDE 35
slide-36
SLIDE 36
slide-37
SLIDE 37

 The flowchart reads three numbers and prints the value

  • f the largest number.
slide-38
SLIDE 38

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

slide-39
SLIDE 39

#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; }

slide-40
SLIDE 40

 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; */

slide-41
SLIDE 41

y = abs(x)

y = (x > 0) ? x : -x;

signum = (x < 0) ? -1 : (x > 0 ? 1 : 0)

slide-42
SLIDE 42

int d = numg / 25; charg =

(d == 0) ? ‘D’ : ((d == 1) ? ‘C’ : (d == 2) ? ‘B’ : ‘A’);

slide-43
SLIDE 43

 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

slide-44
SLIDE 44

 ; 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; }

slide-45
SLIDE 45

 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
slide-46
SLIDE 46

 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> }

slide-47
SLIDE 47

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> }

slide-48
SLIDE 48

 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\

slide-49
SLIDE 49

 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

slide-50
SLIDE 50

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);

slide-51
SLIDE 51

case '*': res = opd1 * opd2; break; default: printf("Invalid operator \n"); return -1; } printf("%d %c %d = %d\n", opd1, opr, opd2, res); return 0; }

slide-52
SLIDE 52

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> }

slide-53
SLIDE 53

 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>

slide-54
SLIDE 54

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; }

slide-55
SLIDE 55

 All values used in case should be different

switch(i){ //Error case 1: … case 2: … case 1: …

slide-56
SLIDE 56

 All values must be value, not expression of variables

switch(i){ //Error case j: … case 2: … case k+10: …

slide-57
SLIDE 57

 While  Do while  For

slide-58
SLIDE 58
  • 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
slide-59
SLIDE 59
  • 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.

slide-60
SLIDE 60
  • 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).

slide-61
SLIDE 61
  • 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

slide-62
SLIDE 62
  • 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.

slide-63
SLIDE 63
  • 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.
slide-64
SLIDE 64
  • 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

slide-65
SLIDE 65
  • 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.”

slide-66
SLIDE 66
  • 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.

slide-67
SLIDE 67
slide-68
SLIDE 68
  • 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
slide-69
SLIDE 69
  • 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

slide-70
SLIDE 70

while ( <expression> ) <statements>

slide-71
SLIDE 71

ددع هک دیسیونب یا همانرب 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; }

slide-72
SLIDE 72

#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; }

slide-73
SLIDE 73

 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 */

slide-74
SLIDE 74

do <statements> while (<expression>);

slide-75
SLIDE 75

#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; }

slide-76
SLIDE 76

#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; }

slide-77
SLIDE 77

for(<expression1>;<expression2>; <expression3>) <statements>

slide-78
SLIDE 78

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

slide-79
SLIDE 79

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num _

slide-80
SLIDE 80

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 1 _

slide-81
SLIDE 81

num 1 _

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

slide-82
SLIDE 82

num 1 1 _

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

slide-83
SLIDE 83

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 2 1 _

slide-84
SLIDE 84

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 2 1 _

slide-85
SLIDE 85

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 2 1 2 _

slide-86
SLIDE 86

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 3 1 2 _

slide-87
SLIDE 87

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 3 1 2 _

slide-88
SLIDE 88

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 3 1 2 3 _

slide-89
SLIDE 89

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 4 1 2 3 _

slide-90
SLIDE 90

Example: for (num = 1; num <= 3; num++ ) printf(“%d\t”, num); printf(“have come to exit\n”);

num 4 1 2 3 _

slide-91
SLIDE 91

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_

slide-92
SLIDE 92

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; }

slide-93
SLIDE 93

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; }

slide-94
SLIDE 94

int n, number; printf("Enter n: "); scanf("%d", &n); for(number = 2; number <= n; number += 2) printf("%d \n", number); return 0; }

slide-95
SLIDE 95
  • 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 )

slide-96
SLIDE 96
  • 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
slide-97
SLIDE 97
  • 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.

slide-98
SLIDE 98
  • <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++) ;

slide-99
SLIDE 99
  • <statement> in loops can be loop itself

while(<expression0>) for(<expression1>; <expression2>;<expression3>) <statements> for(<expression1>; <expression2>;<expression3>) do <statements> while(<expression>);

slide-100
SLIDE 100
  • A program that takes n and m and prints

*** ….* (m * in each line) *** ….* … *** ….* (n lines)

slide-101
SLIDE 101

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; }

slide-102
SLIDE 102
  • A program that takes n and prints

* ** *** (i * in i-th line) *** ….* (n lines)

slide-103
SLIDE 103

#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; }

slide-104
SLIDE 104
  • 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"); }

slide-105
SLIDE 105
  • 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.
slide-106
SLIDE 106
  • 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);

slide-107
SLIDE 107
slide-108
SLIDE 108

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; } }

slide-109
SLIDE 109
slide-110
SLIDE 110

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);

slide-111
SLIDE 111
  • 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);

slide-112
SLIDE 112
slide-113
SLIDE 113

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
slide-114
SLIDE 114
  • 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

slide-115
SLIDE 115
  • Don’t modify forloop controller in loop body

for(i = ... i--; 0; i < 10; i++){ //Bug }

  • Take care about wrong control conditions
  • < vs. <=
  • = vs. ==

int b = 10; while(a = b){//it means while(true) scanf("%d",&a) … {