0% found this document useful (0 votes)
2 views

PPS Chapter 5 Functions

This document covers the fundamentals of functions in C programming, including concepts, types, and advantages of both predefined and user-defined functions. It explains function prototypes, parameter passing methods, and provides examples of function usage, including recursion and macros. Additionally, it discusses pre-processing directives and their role in the compilation process.

Uploaded by

cchvcuj5r1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PPS Chapter 5 Functions

This document covers the fundamentals of functions in C programming, including concepts, types, and advantages of both predefined and user-defined functions. It explains function prototypes, parameter passing methods, and provides examples of function usage, including recursion and macros. Additionally, it discusses pre-processing directives and their role in the compilation process.

Uploaded by

cchvcuj5r1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

3110003

PROGRAMMING FOR PROBLEM SOLVING

UNIT-5

Functions
1
Created by Trushita Patel
Topics to be covered:
• Concepts function • Parameter
• Standard library passing
function
• Calling a
• User defined functions
function
• Prototypes
• Recursive
• Definition of function
• Parameters function
• Macros
• Pre-
Created by Trushita Patel
processing 2
Concepts of Function
• ” A function is a group of statements that together perform a
task.”
• Every C program has at least one function, which is main(),
• you can divide up your code into separate functions.
⮚ Why we need functions in C?
• To improve the readability of code.
• Improves the reusability of the code, same function can be used in
any program rather than writing the same code from scratch.
• Debugging of the code would be easier if you use functions, as errors
are easy to be traced.
Created by Trushita Patel 3

• Reduces the size of the code, duplicate set of statements are replaced
Types of functions
• There are two types of function in C programming:
1) Pre-defined standard library functions
2) User-defined functions

1) Predefined standard library functions:


• The standard library functions are built-in functions in C
programming such as puts(), gets(), printf(), scanf() etc
• These are the functions which already have a definition in
header files (.h files like stdio.h), so we just call them whenever
there is a need to use them.

2) User Defined functions :


• The functions that we create in a program are known as user
defined functions.
Created by Trushita Patel 4
C Standard library functions
• The prototype and data definitions of these functions are present in their
respective header files.
• To use these functions we need to include the header file in our program.
• For example, if you want to use the printf() the header file <stdio.h>
should be included.

#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}
⮚ Advantages
• use library functions is simply
• The functions are optimized for performance
• It saves considerable development time
Created by Trushita Patel
• The functions are portable 5
Program
• To compute the square root of a number, you can use the sqrt() library
function. The function is defined in the math.h header file.

#include <stdio.h>
#include <math.h>
void main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
root = sqrt(num);
printf("Square root of %.2f = %.2f", num, root);

Created by Trushita Patel 6


Library Functions in Different
Header Files
C Header Files
<assert.h> Program assertion functions
<ctype.h> Character type functions
<locale.h> Localization functions
<math.h> Mathematics functions
<setjmp.h> Jump functions
<stdarg.h> Variable arguments handling functions
<stdio.h> Standard Input/Output functions
<stdlib.h> Standard Utility functions
<string.h> String handling functions
<time.h> Date time functions

Created by Trushita Patel 7


User-defined function
• You can also create functions as per your need. Such functions created
by the user are known as user-defined functions.

⮚ How user-defined function works?


#include <stdio.h>
void functionName()
{
return a+b;

}
void main()
{
... .. ...
functionName(2,3);
... .. ...
Created by Trushita Patel
} 8
User-defined function
⮚ Advantages of user-defined function
• The program will be easier to understand, maintain and debug.
• Reusable codes that can be used in other programs
• A large program can be divided into smaller modules. Hence, a large
project can be divided among many programmers.

Created by Trushita Patel 9


Function Prototype
• There are three aspects of a C
function.
Prototype Syntax
Function declaration: A function must be
declared globally in a c program to tell the return_type function_name
compiler about the function name, function (argument list);
parameters, and return type.
Ex: int sum(int,int);
Function call: Function can be
function_name (argument_list);
called from anywhere in the
program. The parameter list must Ex: sum(21,14);
not differ in function calling and
function declaration. We must
pass the same number of
parameters as it is declared in
the function declaration.
Created by Trushita Patel 10
Function Prototype
Prototype Syntax
Function definition: It contains the return_type function_name (argument
actual statements which are to be list) {
executed. It is theFunction
most important aspect ………..
call Function can be called from
to which the control comes when
anywhere in thethe function
program. body; list must
The parameter
function is called. not
Here, we must
differ notice calling
in function ……….. and function
that only one value can be returned
declaration. We mustfrompass
} the same number of
the function. functions as it is declared in the function
declaration. Ex: int sum (int a,int b)
function_name (argument_list)
{
printf(“%d”, a+b);
}

Created by Trushita Patel 11


Function Prototype keyword
•Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.

•Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.

•Parameters − A parameter is like a placeholder. When a function is


invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.

•Function Body − The function body contains a collection of statements that


Created by Trushita Patel 12
define what the function does.
Program
#include <stdio.h>

void introduction()
{
printf("Hi\n");
printf("My college name is gec patan\n");
printf("How are you?");
}

void main()
{
introduction();
}

Created by Trushita Patel 13


Program
#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
sum = num1+num2;
return sum;
}
void main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
int ans = addition(var1, var2);
printf ("Output: %d", ans);
}
Created by Trushita Patel 14
Function Arguments/Parameters
• There are Two way to pass parameters
in function.
Syntax
Pass by Value: In the call by value
method the actual arguments are copied return_type function_name
to the formal arguments, hence any (argument list);
operation performed by function on
arguments doesn’t affect actual Ex: int sum(int,int);
parameters.
Call by reference method: Unlike
function_name (argument_list);
call by value, in this method, address
of actual arguments (or parameters) Ex: sum(21,23);
is passed to the formal parameters,
which means any operation
performed on formal parameters
affects the value of actual
Created by Trushita Patel 15
parameters.
Program for Pass by Value:
In C, parameters are always passed by value. Parameters are always passed
by value in C. For example. in the below code, value of x is not modified using
the function fun().
#include <stdio.h>
void fun(int x)
{
x = 30;
}

int main(void)
{
int x = 20;
fun(x);
printf("x = %d", x);
return 0;
} Created by Trushita Patel 16
Program for Pass by Reference:
In C, Parameters are always passed by reference in C. For example. in the
below code, value of x is modified using the function fun().
# include <stdio.h>
void fun(int *(2046))
{
*ptr = 30;
}

int main()
{
int x = 20;
fun(&x);
printf("x = %d", x);

return 0;
} Created by Trushita Patel 17
Different aspects of function
calling
• function without arguments and without return value 🡪 void f1( )
• function without arguments and with return value 🡪 int f1( )
• function with arguments and without return value 🡪 void f1(a)
• function with arguments and with return value 🡪 int f1(a)

Created by Trushita Patel 18


⮚ Example for Function without argument and return
value
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(“cprogram");
}

Created by Trushita Patel 19


⮚ Example for Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Created by Trushita Patel 20
⮚ Example for Function with argument and without
return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Created by Trushita Patel 21
⮚ Example for Function with argument and with return
value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
} Created by Trushita Patel 22
Calling a function,
• To use a function, you will have to call that function to perform the
defined task.
• When a program calls a function, the program control is transferred to the
called function.
• A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached,
• it returns the program control back to the main program.
• To call a function, you simply need to pass the required parameters along
with the function name,
• and if the function returns a value, then you can store the returned value.
Created by Trushita Patel 23
Calling a function,
#include <stdio.h> int main ()
int max(int num1, int {
num2)
{ int a = 100;
int result; int b = 200;
if (num1 > int ret;
num2)
{ /* calling a function to get max value */
result ret = max(a, b);
= num1;
} printf( "Max value is : %d\n", ret );
else
{ return 0;
result }
= num2;
{
Created by Trushita Patel 24
return result;
}
Recursive function
• Recursion is the process of repeating void recursion()
items in a self-similar way. {
recursion(); /* function calls
• In programming languages, if a itself */
program allows you to call a function }
int main()
inside the same function, then it is {
called a recursive call of the function. recursion();
}
• a function to call itself.
• But while using recursion,
programmers need to be careful to
define an exit condition from the
Created by Trushita Patel 25
function, otherwise it will go into an
infinite loop.
Program
#include <stdio.h>
int factorial (int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
void main()
{
int i = 12;
printf("Factorial of %d is %d\n", i,
factorial(i));

}
Created by Trushita Patel 26
Program for Fibonacci Series
#include <stdio.h> void main()
int fibonacci(int i) {
{ int i;
if(i == 0) for (i = 0; i < 10; i++)
{ {
return 0; printf("%d\t\n", fibonacci(i));
} }

if(i == 1) }
{
return 1;
}
return (fibonacci(i-1) +
fibonacci(i-2));
}

Created by Trushita Patel 27


Macros
• Macros in C are string replacements commonly used to define constants.
• Whenever you have to use value of pi in your code you can simply write PI
instead of writing lengthy value of pi again and again.
• Basically macros are one of the Preprocessor directives available in C.

Created by Trushita Patel 28


Predefined Macros
ANSI C defines a number of macros. Although each one is available for use
in programming, the predefined macros should not be directly modified.
Sr.No. Macro & Description
1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.
2 __TIME__
The current time as a character literal in "HH:MM:SS" format.
3 __FILE__
This contains the current filename as a string literal.
4 __LINE__
This contains the current line number as a decimal constant.
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.

Created by Trushita Patel 29


Program
#include <stdio.h>
int main() { OUTPUT:-
File :test.c
printf("File :%s\n", __FILE__ ); Date :Jun 2
printf("Date :%s\n", __DATE__ ); 2012
printf("Time :%s\n", __TIME__ ); Time :03:36:24
printf("Line :%d\n", __LINE__ ); Line :8
printf("ANSI :%d\n", __STDC__ ); ANSI :1

Created by Trushita Patel 30


Pre-processing
• The C Preprocessor is not a part of the compiler, but is a separate step in
the compilation process.
• All preprocessor commands begin with a hash symbol (#).
• It must be the first nonblank character, and for readability, a preprocessor
directive should begin in the first column.
• Ex:-#define PI 3.14
#include <stdio.h>

Created by Trushita Patel 31


Pre-processing
Sr.No. Directive & Description 7 #else
1 #define The alternative for #if.
Substitutes a preprocessor macro.
8 #elif
2 #include #else and #if in one statement.
Inserts a particular header from another
file. 9 #endif
Ends preprocessor conditional.
3 #undef
Undefines a preprocessor macro. 10 #error
Prints error message on stderr.
4 #ifdef
Returns true if this macro is defined. 11 #pragma
5 #ifndef Issues special commands to the
Returns true if this macro is not defined. compiler, using a standardized
method.
6 #if
Tests if a compile time condition is true.
Created by Trushita Patel 32

You might also like