8 Functions
8 Functions
Introduction
A function is a sub program that is executed once
functions:
- pre-defined (inbuilt) functions
- User-defined functions
Pre-defined
Functions
Were created by the programming language developers to
- Input/output functions
- String functions
- Math functions
Input/Output Functions
Input/Output files/libraries containing I/O functions include:
functions.
Function Action
#include<string.h>
#include<stdio.h>
main() {
char mystring[10];
scanf("%s", &mystring);
return 0;
}
// Finds the length of a string
#include<string.h>
#include<stdio.h>
main() {
char mystring[10]; int x;
printf("Enter your string ");
scanf("%s", &mystring);
X = strlen(mystring);
printf(“String length is %d", x);
return 0;
}
#include<math.h>
#include<stdio.h>
main() {
int x;
double ans;
printf("Enter number");
scanf("%d", &x);
ans = sqrt(x); // function call
printf(“Square root is %f", ans);
return 0;
}
Math Functions
Use math.h file.
sqrt
round
truc
sin
tan
cos
Large programs are divided in functional parts, and each of
further investigations.
program.
All the six elements are grouped together into two parts,
namely; function header and function body.
General Format Of A User-defined Function
elements:
function type (also called return type);
Function Name is any valid C identifier and thus must follow the
will receive data sent by the calling program. They serve as input
data to the function to carry out the specified task.
Function Body
Contain the declaration and statements necessary for performing
function
function.
Example
}
Function Call
A function may be called by simply using the name followed
Example
{ Scanf (“%d”,&b);
return ans; }
int main()
# include <stdio.h> scanf(“%d”,&rad);
float area(int r) ar=area(rad); // function call
{ printf(“Answer is %f”, ar);
int ans; float pi=3.14; return 0;
ans= pi*r*r; }
return ans;
}
int main()
{
int rad; float ar;
printf (“Enter radius”);