43_pdfsam_lecture2 - Math functions Warning: ^ is the XOR...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Math functions Warning: ^ is the XOR operator, not exponentiation! e.g. In C, 2 ^ 3 != 8 (instead, 2 ^ 3 == 1) Many math functions available in math.h : p ow(a, b) : computes exp(a) : computes cos, sin, tan acos, asin, atan etc. ea ab log(a) : natural logarithm Functions Purpose of functions Breaks a program into pieces that are easier to understand Makes recursive algorithms possible to implement Promotes code reuse Disadvantage of functions Function calls add some memory and time overhead Functions in C Similar to methods in Java But C functions do not belong to a class. Every function is visible everywhere in the program. A simple function int power( int base, int exp ) { ssint i, p = 1; ssfor( i = 1; i <= exp; i++ ) ssp *= base; ssreturn p; } This function takes 2 integers as arguments, returns an int Variables declared inside power (base, exp, p) are local variables and not visible outside the function return statement is used to specify return value Simple function in context int power( int base, int exp ); void main() { ssint i = 3, j = 4; ssprintf( %d^%d is %d.\n, i, j, power(i, j)); } int power( int base, int exp ){ ssint i, p = 1; ssfor( i = 1; i <= exp; i++ ) ssssp *= base; ssreturn p; } Function Return values If a function returns type void, then no return statement is needed If a function returns another type, then a return statement is required along all possible execution paths What does this code do? int foo( int arg ); int foo( int arg ) { ssif (arg == 1) return 0; } void main() { ssprintf( %d\n, foo(0) ); } ...
View Full Document

Page1 / 5

43_pdfsam_lecture2 - Math functions Warning: ^ is the XOR...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online