Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lab 8 User Defined Function.

Similar presentations


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

1 Lab 8 User Defined Function

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

3 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

4 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()

5 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()

6 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

7 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()

8 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

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


Download ppt "Lab 8 User Defined Function."

Similar presentations


Ads by Google