Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods and Data Passing

Similar presentations


Presentation on theme: "Methods and Data Passing"— Presentation transcript:

1 Methods and Data Passing
Module 5 Methods and Data Passing 4/9/2019 CSE 1321 Module 5

2 Why have functions? CREATE average, userNum1, userNum2
PRINT (“Please enter the 2 numbers”) READ userNum1 READ userNum2 average = (userNum1 + userNum2) / 2 // a lot of other code // more code here, then

3 Header/Body Example # Top line is the header def sum(num1, num2):
# Body begins here sum = for i in range(num1, num2 + 1): sum += i return sum # Body ends here 4/9/2019 CSE 1321 Module 4

4 Method Signature # Signature is sum(num1, num2) def sum(num1, num2):
# Body begins here sum = for i in range(num1, num2 + 1): sum += i return sum # Body ends here 4/9/2019 CSE 1321 Module 4

5 Psuedocode - A Bad Solution (where is the repeated code?)
sum ← 0 FOR (i ← 1 i <= 10 i ← i+1) sum ← sum + i ENDFOR PRINT("Sum from 1 to 10 is “, sum) FOR (int i ← 20 i <= 30 i ← i+1) PRINT("Sum from 20 to 30 is “, sum) for (int i ← 35 i <= 45 i ← i+1) PRINT("Sum from 35 to 45 is “, sum) 4/9/2019 CSE 1321 Module 5

6 METHOD MAIN BEGIN CREATE result ← SUM(arguments: 1,10) PRINT("Sum from 1 to 10 is:”, result) result ← SUM(arguments: 20,30) PRINT("Sum from 20 to 30 is:”, result) result ← SUM(arguments: 35,45) PRINT("Sum from 35 to 45 is:”, result) END MAIN METHOD SUM(parameters: num1, num2) BEGIN CREATE sum ← FOR (i ← num1, i <= num2, i ← i+1 ) sum ← sum + i ENDFOR RETURN sum END SUM Ps 4/9/2019 CSE 1321 Module 5

7 Python Example – Method Sum
def sum(num1, num2): sum = 0 for i in range(num1, num2 + 1): sum += i return sum def main(): print("Sum from 1 to 10 is ", sum(1, 10)) print("Sum from 20 to 30 is ", sum(20, 30)) print("Sum from 35 to 45 is ", sum(35,45)) main() #Call the main function 4/9/2019 CSE 1321 Module 5

8 Psuedocode - Method Max
METHOD MAIN BEGIN CREATE i ← 5 CREATE j ← 2 CREATE k ← max(i, j) PRINT("The maximum of ", i , " and ” , j ," is ", k) END MAIN METHOD MAX(parameters: num1, num2) BEGIN CREATE result if (num1 > num2) result ← num1 else result ← num2 RETURN result END MAX 8 4/9/2019 CSE 1321 Module 5

9 Python – Method Max def max(num1, num2): result = 0 if(num1 > num2): result = num1 else: result = num2 return result def main(): i=2 j=5 print("Max between ",j," and ",i," is ",max(i,j)) main() #Call to the main function 4/9/2019 CSE 1321 Module 5


Download ppt "Methods and Data Passing"

Similar presentations


Ads by Google