log() Function Example in C Programming

In this source code example, we will see how to use the log() function in C programming with an example.

log() Function Overview

The log() function in C is utilized to calculate the natural logarithm (base e) of a number. The natural logarithm is the inverse operation of the exponential function and is a fundamental concept in mathematics, physics, engineering, and many other disciplines. The function is available in the math.h library. 

Key Points: 

- To use the log() function, make sure to include the math.h header. 

- The function computes the logarithm with base e, where e is approximately 2.71828. 

- The argument provided should be positive. If the value is zero or negative, the function will return a domain error. 

- Don't forget to link the math library with the -lm flag during compilation.

Source Code Example

#include <stdio.h> #include <math.h> // Required for log() int main() { double value, result; // Request input from the user printf("Enter a positive value to compute its natural logarithm: "); scanf("%lf", &value); if(value <= 0) { printf("Error: The input should be a positive number.\n"); return 1; } // Calculate the natural logarithm of the entered value result = log(value); // Display the result printf("Natural logarithm of %.2lf is: %.2lf\n", value, result); return 0; } 

Output

Enter a positive value to compute its natural logarithm: 2.71828 Natural logarithm of 2.72 is: 1.00 

Explanation

1. We begin by including the required header files: stdio.h for standard input and output functions and math.h to access the log() function.

2. Inside the main() function, we prompt the user to input a value.

3. A condition checks if the entered value is positive. If not, an error message is displayed, and the program terminates.

4. If a positive value is provided, the log() function is used to determine its natural logarithm.

5. The computed result is then printed to the console.


Comments