70 likes | 188 Vues
Functions are essential code blocks that execute specific operations, enhancing program efficiency by avoiding redundancy. They act as sophisticated statements that yield consistent results when called. Utilizing existing functions from libraries, such as the C Standard Library, allows developers to build on established code. For example, to compute the cosine of 90°, including the math.h header grants access to the prepackaged `cos()` function, simplifying complex calculations. Understanding user-defined functions will also empower programmers to create custom solutions for unique problems.
E N D
What arefunctions? 1. A piece of code that performs an operation that can be used by the main program or by other functions 2. A sophisticated if –else statement that always goes into the else part and never into the if part Just some stuff the compiler uses and the user never has to use or see 4. An out of this world thrill ride at the Walt Disney World Resort in Orlando, FL!!!
Using Functions • Avoid re-inventing the wheel • Using existing functions as building-blocks to create new programs • “Prepackaged” functions in the C Standard Library can be used. • User-defined functions can also be used (talk about this next lecture).
Example: Suppose you want to find cos(90°). • 90° = π/2 • One way would be to calculate the power series: • Or, you can just use include the math.h header which • contains a built in cosine function.
For your in class assignment • Use #include math.h • Take a look at /usr/include/math.h and note the • #define • Use M_PI for pi or define your own pi. • Use the function acos(argument) to find the inverse cosine • In order to compile using the math library, you must use a compiler flag –lm: • gccprogram.c –lm –o executable • Or • gccprogram.c –o executable –lm (this way is better)
Law of Cosines Leg 1 Leg 2 Hypotenuse