# Lab 8 User Defined Function.

## Presentation on theme: "Lab 8 User Defined Function."— Presentation transcript:

Lab 8 User Defined Function

What is a function? main() { . } examples: cos(a); sin(a); pow(a,b);
{.. }

Using a function Declaring name and type of function
#include <stdio.h> output function (input) void main (void) {………. function() ……….. .} {…. …… …} Declaring name and type of function Using the function within main() Writing the actual function

Function example #include <stdio.h> #include <math.h>
void main (void) { int x=10,n=3,r; printf("This line will appear on your screen\n"); r=pow(x,n); printf("\nr = %d\n\n",r); } function f1() function f2()

no variable values are exchanged between main() and f1()
Function example: f1() #include <stdio.h> #include <math.h> void f1 (void); void main (void) {int x=10,n=3,r; f1(); r=pow(x,n); printf("\nr = %d\n\n",r); } void f1 (void) { printf("This line will appear on your screen\n"); no variable values are exchanged between main() and f1()

Function example: f2() #include <stdio.h>
#include <math.h> void f1 (void); void f2 (int a, int b); void main (void) {int x=10,n=3; f1(); f2(x,n); } void f1 (void) { printf("This line will appear on your screen\n"); } void f2 (int a, int b) { int r; r=pow(a,b); printf("\nr = %d\n\n",r); } a and b are two integer inputs to function f2() f2() is given two integer inputs r is defined

Function example: f2() contd
#include <stdio.h> #include <math.h> void f1 (void); int f2 (int a, int b); void main (void) {int x=10,n=3,result; f1(); result=f2(x,n); printf("\nr = %d\n\n",result);} void f1 (void) { printf("This line will appear on your screen\n"); } int f2 (int a, int b) { int r; r=pow(a,b); Return r;} value of r calculated by f2() is stored in result f2() returns an integer value of r is returned to main()

Factorial Write a program to calculate the factorial of an inputted number n n! = n * n-1 * n-2 * …..* 2 * 1 Examples: 5! = 120 4! = 24

Binomial Coefficient Write a program that calculates the binomial coefficient Three factorials are needed Calculate factorials through a function called factorial()