chapter2_7
chapter2_7
11
Functions in C
7.1. Introduction
7.3. Functions
2
Introduction: Divide and conquer
3
Program Modules in C
FUNCTIONS
4
Where to write function definition?
5
Function definition before the main
#include<stdio.h>
int square(int x){
int y;
y = x * x;
return y;
}
main(){
int i;
for (i=0; i<= 10; i++)
// function call
printf(“%d ”, square(i));
}
6
Function definition with prototype
#include<stdio.h>
float square(float x);
main()
{int i;
for (i=0; i<= 10; i++)
printf("\n%f",square(i));}
float square(float x)
{return x*x;}
7
Function definition
8
Function definitions
9
Function prototype
10
Function Prototypes
• Function prototype
• Function name
• Parameters - what the function takes in
• Return type - data type function returns
• Used to validate functions
• Prototype only needed if function definition comes
after use in program
int maximum( int x, int y, int z);
• Takes in 3 ints
• Returns an int
11
Function calls
• Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
12
Calling Functions: Call by Value and Call by Reference
13
Example: Call_by_reference parameter
#include <stdio.h>
int main() {
int a = 5, b = 100;
printf(“Before: a=%d, b=%d \n\n", a,b);
swap(&a, &b);
printf(“After : a=%d, b=%d \n\n", a, b);
return 0;
}
14
Scope rules
15
Scope Rules
• File scope
• Identifier defined outside functions, known in all functions
• Used for global variables, function definitions, function
prototypes
• Function scope
• Can only be referenced inside a function body
16
Scope Rules
• Block scope
• Identifier declared inside a block
• Block scope begins at definition, ends at right brace
• Used for variables, function parameters (local variables of
function)
• Outer blocks "hidden" from inner blocks if there is a
variable with the same name in the inner block
17
Block Scope
• Execution blocks, delimited with {}, define scopes.
{ int t=5;
{
float t=3.14;
printf("%f",t);
}
printf("%d",t);
}
• Nested functions
#include <stdio.h> 3
#include <stdio.h> 3
int fun(int a){ fun(3)
return a++;
3
}
fun(4)
int main(){ 3
printf("%d\n", fun(fun(fun(3))));
fun(5)
return 0;
}
3
20
Example 3: Result of the following program
#include <stdio.h>
#include <math.h>
float f(float x) {
if(x == 0.0)
return 0;
else
return pow(x,5)+x/fabs(x) * pow(fabs(x), 0.2);
}
int main() {
float a, b, c;
printf(“Enter 3 numbers: "); scanf("%f%f%f", &a, &b, &c);
printf(“Result:%f \n", (f(a) + f(b) + f(c)) / 3);
return 0;
}
22
Example 6: Compute GCD of a list
1. #include <stdio.h>
2. int gcd(int a, int b) {
3. while (a != b){
4. if(a > b) a = a- b;
5. else b = b - a;
6. }
7. return a;
8. }
9. int main() {
10. int A[100], N, i, r;
11. printf(“Number of Elements: "); scanf("%d", &N);
12. for(i=0; i < N; i++) {
13. printf("A[%d] = ", i+1); scanf("%d", &A[i]);
14. }
15. r = A[0];
16. for(i = 1; i < N; i++)
17. r = gcd(r,A[i]);
18. printf(“GCD of the list:%d \n", r);
19. return 0;
20. }
23