Functions contd.. Debugging Syntax Error

4 downloads 93 Views 189KB Size Report
➢Fixable if you learn to read compiler error messages. 1. ▫ Semantic. ➢No easy fix. • Use print statements to our advantage. Syntax Error. ▫ Use the Syntax ...
Debugging

Functions contd..

„

It is highly unlikely that you will write code that will work on the first go

„

Bugs or errors „

Syntax ¾Fixable if you learn to read compiler error messages

Material © Diana Palsetia „

Semantic ¾No easy fix • Use print statements to our advantage

1

Debugging with printf

Syntax Error „

„ „ „

„

//sum positive odd numbers upto n for (i = 1; i 0; i--){ prod = prod * i; return prod; }

6

CIT593

This implies parameters and local variables (variables declared within method) are discarded Hence, this explains the reasoning for scope rules for variables within functions. 7

2

Call by Value „ We

call a function like this:

result = add( 3 , 5 ) ;

Call by value contd.. Actual parameter values are copied into formally defined parameters

int m = -1; int result = absolute(m);

The value of m (i.e. -1) is copied to the formal pparameters

int absolute(int n){ Changing n does not affect m if(n < 0){ n = n * -1; } return n; The value of n is } returned, but the

int add ( int number1, int number2 ) { int sum = number1 + number2 ; return sum ; }

variable n is thrown away CIT593

8

CIT593

9

Functions calling other Functions

Stack

int isLeapYear(int year){ if(year %4 ==0 && (year %100 != 0 || year %400 == 0) return TRUE; else return FALSE; } void leapYearBet(int start, int end){ int x = start; printf("Leap years between %d and %d:\n”, start, end); while(x end) { // base case return 0; } return start + sum(start + 1, end); }

CIT593

16

CIT593

17

5