0% found this document useful (0 votes)
3 views26 pages

04 - Functions

This document provides an overview of functions in C programming, detailing the two types: standard library functions and user-defined functions. It explains the structure of function declarations, definitions, and calls, as well as the concepts of call by value and call by reference. Additionally, it includes examples and practice problems related to function implementation, recursion, and assignments for further learning.

Uploaded by

tasfiatasnim1084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

04 - Functions

This document provides an overview of functions in C programming, detailing the two types: standard library functions and user-defined functions. It explains the structure of function declarations, definitions, and calls, as well as the concepts of call by value and call by reference. Additionally, it includes examples and practice problems related to function implementation, recursion, and assignments for further learning.

Uploaded by

tasfiatasnim1084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

ME 172

Computer Programming Language Sessional

Lecture 4: Functions
Functions

A function is a block of code that performs a specific task.

There are two types of functions in C programming:

1) Standard Library Function &

2) User Defined Function.

The standard library functions are in-built functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc. These functions are defined in the header file. When you
include the header file, these functions are available for use. For example: The printf() is a standard library
function to send formatted output to the screen (display output on the screen). This function is defined
in "stdio.h" header file.

C language allows programmer to define functions. Such functions created by the user are called user-defined
functions.
Library Functions:
◦ Library functions are not required to be written by us
◦ printf and scanf belong to the category of library function

Examples:
Printf(), scanf(), Sqrt(), cos(), strcat(), rand(), etc are some of library functions

#include <stdio.h>
#include <math.h>
int main( )
{
float x, y ; main() calls 3 built-in functions:
scanf(), sqrt() & printf()
scanf("%f", &x);
y=sqrt(x);
printf("Square root of %f is %f\n", x,y);
}
Functions
General Format of User Defined Functions:

⦁ Function declaration or prototype - Informs compiler about the function name,


function parameters and return value’s data type.
⦁ Function call – This calls the actual function
⦁ Function definition – This contains all the statements to be executed.

No Function aspects Syntax

1 Function definition return_type function_name(arguments list)


{ Body of function; }

2 function call function_name ( arguments list );

3 function declaration return_type function_name ( argument list


);
Functions
General Format of User Defined Functions:

int addNumbers(int a,int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}
Functions
Function Prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and return
type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be used in the program.

returnType functionName(type1 argument1, type2 argument2,...);

Syntax of function call


functionName(argument1, argument2, ...);
How functions are called :

⦁ There are two ways that a C function can be called from


a program. They are,
◦ Call by value
◦ Call by reference

Call by value :

◦ In call by value method, the value of the variable is passed to the function as parameter.
◦ The value of the actual parameter can not be modified by formal parameter.
◦ Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.
⦁ #include<stdio.h>
void swap(int a, int b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n); // calling swap function by value
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
Call by Reference :

⦁ In call by reference method, the address of the variable is passed to the


function as parameter.

⦁ The value of the actual parameter can be modified by formal parameter.

⦁ Same memory is used for both actual and formal parameters since only address is used by both
parameters.
#include<stdio.h>
void swap(int *a, int *b); // function prototype, also called function declaration
int main()
• {
• int m = 22, n = 44;
• // calling swap function by reference
•printf("values before swap m = %d \n and n = %d",m,n); swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
Example on function -1
#include<stdio.h>

void print_it(void); prototype for function

void main(void)
{
printf("This is the Main Function");
print_it();
printf("\nBack to Main Function");
}

void print_it(void)
{
printf("\nThis is the print_it Function");
}
Example on function -2
#include<stdio.h>
void sum_of_all(int s);
void main(void)
{
printf("This is the Main Function");
sum_of_all(50);
printf("\nBack to Main Function");
}
void sum_of_all(int s)
{
long int i,sum=0;
for(i=1;i<=s;i++)
sum+=i;
printf("\nsum of all the numbers from 1 to %d is %d",s,sum);
}
Practice Problem:
1
Write a C program to evaluate the factorial of an integer number.
The code must take input from the user and the calculation must be done in a user
defined function.
Solution
#include<stdio.h>
int factorial(int num);
void main(void)
{
int num;
printf("Enter an integer to find its factorial: ");
scanf("%d",&num);
printf("\nThe result is %d", factorial(num));
}

int factorial(int num)


{ int i,j=1;
for(i=1;i<=num;i++)
j = j * i;
return j;
}
Class Performance 1
 Write a C program which will evaluate the value
 of the exponent of a ny n u m b e r.

 Inputs: 1 . B a s e (x)
 2 . Exponent (y)

Output: Result (xy)

Your program will use a separate function to


evaluate the value x y.
function: solution
#include<stdio.h>
int power(int x, int y);

void main(void)
{
int x,y;
printf("Enter the value of the base");
scanf("%d",&x);
printf("\nEnter the value of the exponent");
scanf("%d",&y);
printf("\n\nThe result is %d",power(x,y));
}

int power(x,y)
{
int i,z=1;
for(i=1;i<=y;i++)
z=z*x;
return z;
}
Class performance 2
Write a program in C to find all the prime numbers between two positive
integers. Use separate function to determine the prime number.
Solution
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2); // swap n1 and n2 if n1 > n2
if (n1 > n2)
{ n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2; }
printf("Prime numbers between %d and %d are: ", n1, n2);
for (i = n1 + 1; i < n2; ++i)
{
// flag will be equal to 1 if i is prime
flag = checkPrimeNumber(i);
if (flag == 1)
{
printf("%d ", i);
}
}
return 0;
}
// user-defined function to check prime number int

checkPrimeNumber(int n)
{
int j, flag = 1;
for (j = 2; j <= n / 2; ++j)
{
if (n % j == 0)
{
flag = 0; break;
}
}
return flag;
}
Recursion

“A recursive function is a function that calls itself directly.”

An example of recursive action


Recursion
** Write a program using recursive function that takes an input integer n and determines the sum of the series n +
(n-1) + (n-2) +…+1.

#include <stdio.h>

int sum(int n);

int main()
{ int a,n=5;
a = sum(n);
printf("%d",a);
return 0;
}

int sum(int n)
{
if (n<=1)
return n;
else return (n+sum(n-1));
}
Practice Problem 3

 Find factorial of a number using recursion


factorial using recursion
#include<stdio.h>
int fact(int n)
{ if (n==1) return 1;
else { printf("\n");
printf("fact(%d) = %d * fact(%d)",n,n,n-1);
return (n*fact(n-1));
}}

void main()
{
int x,m;

m = 6;
x = fact(m);

printf("\n");
printf("%d! = %d",m,x);

}
Class performance 3

-Using recursive approach to find GCD (Greatest Common Divisor)


of two numbers.
Solution
#include <stdio.h>
/* Function declaration */
int gcd(int a, int b);
int main()
{
int num1, num2, hcf;
/* Input two numbers from user */
printf("Enter any two numbers to find GCD: ");
scanf("%d%d", &num1, &num2);
hcf = gcd(num1, num2);
printf("GCD of %d and %d = %d", num1, num2, hcf);
return 0; }

/** * Recursive approach of Euclidean algorithm to find GCD of two numbers */


int gcd(int a, int b)
{
if(b == 0) return a;
else
return gcd(b, a%b);
}
Assignments
1) Write a program in C to convert decimal number to binary number using
function.
2) Write a program to evaluate the sine series:
sin(x) = x - x3/3! + x5/5! - x7/7! + ………….10th term
Your program shall use separate functions to evaluate factorial and power.

You might also like