C Function

Mathematical functions

#include <math.h>
void main(void) {
  printf("%f", sqrt(16)); // square root
  printf("%f", ceil(1.4)); // round up (round)
  printf("%f", floor(1.4)); // round up (round)
  printf("%f", pow(4, 3)); // x(4) to the power of y(3)
}

  • abs(x) absolute value
  • acos(x) arc cosine value
  • asin(x) arc sine
  • atan(x) arc tangent
  • cbrt(x) cube root
  • cos(x) cosine
  • the value of exp(x) Ex
  • sin(x) the sine of x
  • tangent of tan(x) angle

Recursive example

int sum(int k);
int main() {
  int result = sum(10);
  printf("%d", result);
  return 0;
}
int sum(int k) {
  if (k > 0) {
    return k + sum(k -1);
  } else {
    return 0;
  }
}

Return value

int myFunction(int x) {
  return 5 + x;
}
int main() {
  printf("Result: %d", myFunction(3));
  return 0;
}
// output 8 (5 + 3)

two parameters

int myFunction(int x, int y) {
  return x + y;
}
int main() {
  printf("Result: %d", myFunction(5, 3));
  // store the result in a variable
  int result = myFunction(5, 3);
  printf("Result = %d", result);
  return 0;
}
// result: 8 (5 + 3)
// result = 8 (5 + 3)

Multiple parameters

void myFunction(char name[], int age) {
  printf("Hi %s, you are %d years old.\n",name,age);
}
int main() {
  myFunction("Liam", 3);
  myFunction("Jenny", 14);
  return 0;
}
// Hi Liam you are 3 years old.
// Hi Jenny you are 14 years old.

Function parameters

void myFunction(char name[]) {
  printf("Hello %s\n", name);
}
int main() {
  myFunction("Liam");
  myFunction("Jenny");
  return 0;
}
// Hello Liam
// Hello Jenny

Call function

// create function
void myFunction() {
  printf("Good evening!");
}
int main() {
  myFunction(); // call the function
  myFunction(); // can be called multiple times
  return 0;
}
// Output -> "Good evening!"
// Output -> "Good evening!"

Function declaration and definition

int main(void) {
  printf("Hello World!");
  return 0;
}

The function consists of two parts

void myFunction() { // declaration declaration
  // function body (code to be executed) (definition)
}

  • Declaration declares the function name, return type and parameters (if any)

* Definition function body (code to execute)

// function declaration
void myFunction();
// main method
int main() {
  myFunction(); // --> call the function
  return 0;
}
void myFunction() {// Function definition
  printf("Good evening!");
}
Comments