CSE109 - LectureSlide - 04 (Functions)
CSE109 - LectureSlide - 04 (Functions)
Computer Programming
Lecture 3:
Functions in C
Khaled Mahmud Shahriar
Assistant Professor
Department of CSE, BUET
**Slightly modified by
Ishrat Jahan
Function
• A function is a block of code that performs a specific task
• May take input
• May return output
• Functions are used to avoid code repetition
• We have already used functions such as
• scanf, printf, gets, puts, getch, sqrt, strcmp etc.
• Known as library functions
• Now we will write our own function
• Knows as a user-defined function
Function
• C program contains at least one function
• main() must be present exactly once in a program
• No limit on number of functions defined
• There can be function which is defined but not called
• There can be function which is declared but not defined
• One function can not be defined inside other function
• Two or more function can not have same name
• Function and variable name can not be same
• No statements can be written outside of function
• Minimal function is
• dummy(){}
Function Structure
ReturnType FunctionName (Parameter List)
{
//Declaration of Local Variables
//Doing some activities
//Return values accordingly
}
A Simple Function
#include <stdio.h>
void myfunc(void); //Prototyping Output
int main(void) In main
{ In myfunc
printf("In main\n"); Back in main
myfunc();
printf("Back in main\n");
Jump to
return 0;
Back to main
function
}
void myfunc(void)
{
printf("In myfunc \n");
}
Where to place the function?
• Above the main function
• Below the main function (but you have to use prototype then!)
Function Prototype
• Function prototype declares a function
• before its use
• prior to its definition
• Ends with semicolon
• Example:
• Function:
void myfunc(void)
{
//block of code
}
• Prototype:
void myfunc(void);
Function Prototype
• Prototype declares three attributes of a function
• Its return type
• Number of parameters
• Type of parameters
• Compiler need to know the type of data returned by the function
• Default int assumed
• Report illegal type conversions
• main does not require prototype
• Function with no parameters should contain the keyword void in prototype
• Variable length argument list
• scanf, printf
• Prototype: int myfunc(int a, …);
Declaration Vs. Definition
• Declaration: specifies the type of the object
• Function prototype
• Definition: causes storage for an object to be created
• Function: which contains the body is definition
• It is legal to define a function fully before its use
• Eliminates need of separate prototype
Function Arguments
• To take arguments a function must have special variables
• Argument:
• The value that is passed to a function
• Formal parameter
• The variable that receive the value of the argument inside the function
• Local variables of a function can not have same name as formal
parameters
Parameters
#include <stdio.h>
void myfunc(int x, int y); Output
int main(void) In main
{ In myfunc
printf("In main\n");
5 10
myfunc(5,10);
printf("Back in main\n"); Back in main
return 0;
}
void myfunc(int x, int y)
{
printf("In myfunc\n");
printf("%d %d\n",x,y);
}
Parameters
#include <stdio.h>
void myfunc(float x, float y); Output
int main(void) In main
{ In myfunc
printf("In main\n");
myfunc(5,7); 5.000000 7.000000
printf("Back in main\n"); Back in main
return 0;
}
void myfunc(float x, float y)
{
printf("In myfunc\n");
printf("%f %f\n",x,y);
}
Parameters
#include <stdio.h>
int myfunc(int x, int y); Output
int main(void) In main
{
int a,x,y; In myfunc
scanf("%d %d",&x,&y);//x=5, y=7 75
printf("In main\n"); Back in main
myfunc(y,x);
printf("Back in main\n"); 57
printf("x=%d y=%d\n",x,y);
return 0;
}
void myfunc(int x, int y)
{
printf("In myfunc\n");
printf("x=%d y=%d\n",x,y);
}
Return Types
#include <stdio.h>
float myfunc(int x, int y);
int main(void)
Output
{ In main
int x,y; In myfunc
float a;
scanf("%d %d",&x,&y); /x=5, y=7
57
printf("In main\n"); Back in main
a=myfunc(x,y); Result: 12
printf("Back in main\n");
printf("Result: %f\n",a);
5 10
printf("Result: %d",myfunc(5,10)); Result: 15
return 0;
}
float myfunc(int x, int y)
{
printf("In myfunc\n");
printf("%d %d\n",x,y);
return (x+y);
}
Return
• If no return type specified: default int assumed
• when the return statement is encountered: the function returns the
control to the caller immediately
• return statement can be used without return value
• return ;
• Used mostly by void functions
• If the return value is not assigned to anything it is lost, but no harm
done
Return
• More than one values can not be returned
• return a, b;
• Reference can be used
• Discussed later
Function Call From Function
#include<stdio.h> int calculateVolume(int x,int y, int z)
{
int calculateArea(int x,int y); int m,p;
int calculateVolume(int x,int y, int z); printf("In calculateVolume Func: x -->
address: %d, value: %d\n",&x,x);
int main() printf("In calculateVolume Func: y -->
{ address: %d, value: %d\n",&y,y);
int a,b,c,res; printf("In calculateVolume Func: z -->
printf("Give two values:\n"); address: %d, value: %d\n",&z,z);
scanf("%d %d %d",&a,&b,&c);
p=calculateArea(x,y);
printf("In main Func: a --> address: m=p*z;
%d, value: %d\n",&a,a); return m;
printf("In main Func: b --> address: }
%d, value: %d\n",&b,b);
printf("In main Func: c --> address: int calculateArea(int x,int y)
%d, value: %d\n",&c,c); {
printf("In calculateArea Func: x -->
res=calculateVolume(a,b,c); address: %d, value: %d\n",&x,x);
printf("In calculateArea Func: y -->
printf("The area is: %d",res); address: %d, value: %d\n",&y,y);
int myfunc(int x)
{
int z;
printf("Func,m,add: %d, val --> %d\n",&m,m);
z= x+m;
return z;
}
Function Scope: Local and Global Variables
#include <stdio.h>
int myfunc(int x);
int m; ///This m is global
int main(void)
{
int a,l;
scanf("%d %d",&l,&m); //l=3, m=5
printf("Main,m,add: %d, val --> %d\n",&m,m);
a=myfunc(l);
printf("Back in main, Result %d\n",a);
return 0;
}
int myfunc(int x)
{
int z,m=10;
printf("Func,m,add: %d, val --> %d\n",&m,m);
z= x+m; ///This m is local m
return z;
}
Function Call
• Call by value
• Have no effect on the argument used to call
• Call by reference
• Address of an argument is copied into the parameter
• By default C uses call by value
Why call by reference?
#include<stdio.h>
void swapValues(int a, int b); Output
int main() 57
{
57
int x,y, arr[10000];
scanf("%d %d",&x,&y);//x=5, y=7
printf("Before Function: x=%d and y=%d\n",x,y);
swapValues(x,y);
printf("After Function: x=%d and y=%d\n",x,y);
return 0;
}
void swapValues(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Call by reference
#include<stdio.h> int sumAll(int a[],int n)
int sumAll(int a[],int n); {
int main() int i,sum=0;
{ printf("In function: a[0] --> address:
int arr[10], i, n, y; %d, value: %d\n",&a[0],a[0]);
scanf("%d",&n); for(i=0;i<n;i++)
for(i=0;i<n;i++) sum=sum+a[i];
{
scanf("%d",&arr[i]); a[0]=50;
} n=100;
printf("In main: arr[0] --> address: %d, printf("In function: n --> address: %d,
value: %d\n",&arr[0],arr[0]); value: %d\n",&n,n);
printf("In main: n --> address: %d, value:
%d\n",&n,n); return sum;
y=sumAll(arr,n); }
printf("Back In main: n --> address: %d,
value: %d\n",&n,n);
printf("Back In main: arr[0] --> address:
%d, value: %d\n",&arr[0],arr[0]);
printf("Back In main: The sum is: %d",y);
return 0;
}
Call by reference
#include<stdio.h> int sumAll(int a[][10],int n, int k)
int sumAll(int a[][10],int n,int k); {
int main() int i,j,sum=0;
{
int arr[10][10], i, j, n, k, y; printf("In function: a[0][0] --> address:
scanf("%d %d",&n, &k); %d, value: %d\n",&a[0][0],a[0][0]);
for(i=0;i<n;i++) printf("In function: a[1][0] --> address:
{ %d, value: %d\n",&a[1][0],a[1][0]);
for(j=0;j<k;j++)
{ for(i=0;i<n;i++)
scanf("%d",&arr[i][j]); {
} for(j=0;j<k;j++)
} {
printf("In main: arr[0][0] --> address: sum=sum+a[i][j];
%d, value: %d\n",&arr[0][0],arr[0][0]); }
printf("In main: arr[1][0] --> address: }
%d, value: %d\n",&arr[1][0],arr[1][0]);
y=sumAll(arr,n,k); return sum;
}
printf("Back in main: The sum is: %d",y);
return 0;
}
Function Practice Problem: Sum of Factors
#include<stdio.h> int factorSum(int n) {
int i;
int main() { int sum = 0;
int n, fsum; for ( i = 1; i <= n; i++) {
printf("Enter n: "); if ( n % i == 0) {
scanf("%d", &n); sum = sum + i;
fsum = factorSum(n); }
printf("Sum of factor of %d is %d\ }
n", n, fsum); return sum;
return 0; }
}
Function Practice Problem: Prime Detection
#include<stdio.h> int isPrime(int n) {
int i;
int main() { for ( i = 2; i * i <= n; i++) {
int i, n, c; if ( n % i == 0) {
printf("Enter n: "); return 0;
scanf("%d", &n); }
c = isPrime(n); }
if (c == 1) { return 1;
printf("Prime\n"); }
}
else {
printf("Not Prime\n");
}
return 0;
}
Function Practice Problem: List of Prime Numbers
#include<stdio.h> int isPrime(int n) {
int j;
int main() { for ( j = 2; j * j <= n; j++) {
int i, j, n, c; if ( n % j == 0) {
printf("Enter n: "); return 0;
scanf("%d", &n); }
printf("List of Prime Numbers: "); }
for ( i = 1; i <=n; i++) { return 1;
c = isPrime(i); }
if (c == 1) printf("%d ", i);
}
printf("\n");
return 0;
}
Function Practice Problem: List of Perfect Numbers
#include<stdio.h> int isPerfect(int n) {
int s = 0;
int main() { int j;
int i, j, n, c; for ( j = 1; j< n; j++) {
printf("Enter n: "); if ( n % j == 0) {
scanf("%d", &n); s = s + j;
printf("List of Perfect Numbers: "); }
for ( i = 1; i <=n; i++) { }
c = isPerfect(i); if ( s == n) {
if (c == 1) printf("%d ", i); return 1;
} }
printf("\n"); else return 0;
return 0; }
}
Function Practice Problem: Count Even Elements in an Array
#include<stdio.h> int evencount(int a[], int n) {
int i;
int main() { int cnt = 0;
int i, n, count; for ( i = 0; i < n; i++) {
printf("Enter number of elements: "); if ( a[i] % 2 == 0) {
scanf("%d", &n); cnt++;
int a[n]; }
printf("Enter the numbers: "); }
for (i = 0; i < n; i++) { return cnt;
scanf("%d", &a[i]); }
}
count = evencount(a, n);
printf("Total number of even elements
is %d\n", count);
return 0;
}
Solution to Practice Problem 1: Prime Factorization of a
Number
#include<stdio.h> int isPrime(int n) {
int i;
int main() { for ( i = 2; i * i <= n; i++) {
int i, n, k; if ( n % i == 0) {
printf("Enter n: "); return 0;
scanf("%d", &n); }
}
for(i=2;i<n/2;i++){ return 1;
if(isPrime(i) && n%i==0){ }
k=exponent(n,i);
printf("%d^%d*",i,k); int exponent(int n, int x)
} {
} int divisor=x;
int k=0;
return 0;
} while(n%divisor==0){
k++;
divisor*=x;
}
return k;
}
More Practice Problems
• Write a C program to find the xth power of any number using function.
• Write a C program to find whether a number is palindrome or not
using function.
Recursive Function (Recursion)
int main()
{
recursion();
return 0;
}
void recursion()
• A function calling itself is #include<stdio.h> {
… … …
}
Ref: https://www.programiz.com/c-programming/c-recursion
Recursion Practice Problem: Factorial Calculation
#include<stdio.h>
int Fact(int n);
int main()
{
int num, res;
scanf("%d",&num);
res=Fact(num);
printf("Result: %d\n",res);
return 0;
}
int Fact(int n)
{
if(n==0)
return 1;
else
return n*Fact(n-1);
}
Recursion Practice Problem: Digit Sum
#include<stdio.h>
int digitsum(int n);
int main()
{
int N;
printf("Enter a number: ");
scanf("%d", &N);
printf("Digitsum: %d\n", digitsum(N));
return 0;
}
int digitsum(int n)
{
if ( n ==0 )
return 0;
return n%10 + digitsum(n/10);
}
Recursion Practice Problem: GCD
#include <stdio.h>
int gcd(int n1, int n2);
int main()
{
int n1, n2;
scanf("%d %d", &n1, &n2);
printf("G.C.D is %d.", gcd(n1,n2));
return 0;
}
int Fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return Fib(n-1)+Fib(n-2);
}
Recursion Practice Problem: Towers of Hanoi
void toh(int n, char src, char dst, char tmp)
{
if (n == 1)
{
printf("Move disk 1 from peg %c to peg %c\n", src, dst);
return;
}
toh(n - 1, src, tmp, dst);
printf("Move disk %d from peg %c to peg %c\n", n, src, dst);
toh(n - 1, tmp, dst, src);
}
int main()
{
int N;
printf("Enter number of disks: ");
scanf("%d", &N);
toh(N, 'S', 'D', 'T');
return 0;
}
Animation: http://towersofhanoi.info/Animate.aspx
Acknowledgement
All these slides of this course have been prepared by taking help from numerous
resources. The notable contributors are listed below.
1. Content and organization of many pages have been taken from the lecture slides and
codes of the course CSE110 offered to the Department of EEE that were -
i. primarily created by Johra Muhammad Moosa, Assistant Professor (on leave),
CSE, BUET and
ii. later modified by Madhusudan Basak, Assistant Professor, CSE, BUET
2. Most of the wonderful coding examples have been taken from the course CSE281
offered to the Department of BME instructed by Rifat Shahriyar, Professor, CSE,
BUET (course link).
3. search and all the sites that it made available in response to the course
related queries. Some of the sites are: https://geeksforgeeks.org/,
https://www.tutorialspoint.com, https://www.w3schools.com and the list goes on …
Thank You ☺