#05 (01/31/2024)

C Functions

  1. Example: Alternative to pow(x, y)
    Background
    Here is an example of a C program to compute xy without using pow(a, b).
    #include <stdio.h>
    #include <math.h>
    
    float power(float x, float y)
     {
     return exp(y*log(x));
     }
    
    int main()
    {
     float x,y;
     printf("Enter x and y separated by space =");
     scanf("%f %f",&x,&y);
    
     if (x<0)
      {
      printf("x must be positive !!\n");
       return 0;
       }
    
     printf("%f to power of exponent %f is %f.\n", x, y, power(x,y));
    
     return 0;
    }
    
  2. Variables used in a function are local, i.e. they do not retain the values outside the function.
    #include <stdio.h>
    float f(int n)
     {
      int i; float sum=0;
      for (i=1;i < n;i++) sum=sum+1.0/i;
      return sum;
     }
    
    int main()
    {
     float sum=0;
     int i;
      for (i=1;i < 20;i++) sum=sum+1.0/i/i;
      printf("%f %f\n", sum, f(20));
      return 0;
     }
    
    #include <stdio.h>
    
    int i=20;
    
    void f()
    {
        printf("%d\n",i);
    }
    
    int main()
    {
    
      int i=30;
      printf("%d\n", i);
      f();
      return 0;
    }
    
  3. C functions are recursive (i.e. a function can call its own. Examples follow.)




File translated from TEX by TTH, version 4.03.
On 04 Feb 2024, 21:59.