Implementation in Matlab and C N= 10; tot = 0; totsq = 0; for i=1:N tot = tot+i; totsq = totsq+i^2; end tot totsq int i; int tot = 0; int totsq = 0; for (i=1; i<N; i++) { tot += i; totsq += i*i; } cout << tot << endl; cout << totsq << endl;
Function definition % compute factorial function z = fact(n) % function body z = 1; for i=1:n z = z*i; end // compute factorial int fact(int n) { int i, val = 1; for (i=1; i<=n; i++) { val *= i; } return val; }
Low-level implementation of function call Memory CODE DATA machine code global variables STACK local variable m local variable 1 return location return value n return value 1 parameter x parameter 1 … … … Activation record
Pass by value/reference int i=5, j=10; swap(i,j); cout << i << “ “ << j << endl; Pass by value Pass by reference void swap(int a, int b) { int temp = a; a = b; b = temp; return; } void swap(int& a, int& b) { int temp = a; a = b; b = temp; return; }
Example class Window Data: width, height posx, posy Methods: raise(), hide() select(), iconify() class TextWindow Data: cursor_x, cursor_y Methods: redraw(), clear() backspace(), delete() class GraphicsWindow Data: background_colour Methods: redraw(), clear() fill() class InteractiveGraphicsWindow Data: Methods: MouseClick(), MouseDrag()