SlideShare a Scribd company logo
1 of 34
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
FUNCTIONS
Dr. Yousaf, PIEAS
// Addition of two integers without Function
#include<stdio.h>
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = num1 + num2;
printf("Addition result is %dn",add_result);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// Addition of two integers using
Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0;
}
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Dr. Yousaf, PIEAS
• The function is one of the most important topic to understand in C
programming.
• A function groups a number of program statements into a unit and gives
it a name. This unit can then be invoked (called) from other parts of the
program.
• A function is a sub-unit of a program which performs a specific task.
• Functions are modules in c.
• Functions take arguments (constants values or variables) and may
return a value.
Dr. Yousaf, PIEAS
Functions
Benefits of Functions
• Benefits of functions
– Divide and conquer
• Construct a program from smaller pieces or
components
• Modularize a program (These smaller pieces are called
modules)
• Each piece more manageable than the original program
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new
programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition
Dr. Yousaf, PIEAS
• The most important reason to use functions is to aid
in the conceptual organization of a program. Dividing
a program into functions is, one of the major
principles of structured programming.
• Another reason to use functions is to reduce
program size.
• The function’s code is stored in only one place in
memory, even though the function is executed many
times in the course of the program.
Dr. Yousaf, PIEAS
Benefits of Functions
Functions
• A function receives zero or more parameters,
performs a specific task, and returns none or one
value.
• A function is invoked by its name and parameters.
– No two functions have the same name in your C program.
– The communication between the function and invoker is
through the parameters and the return value.
• A function is independent.
– It is “completely” self-contained.
– It can be called at any places of your code.
• Functions make programs reusable and readable.
Dr. Yousaf, PIEAS
• We have already used functions from the C library –
printf(), gets(), scanf(), strcpy
etc.
• We need to learn to write our own functions
• Programs combine user-defined functions with
library functions
• C standard library has a wide variety of functions
Dr. Yousaf, PIEAS
Functions
More Terminologies
Dr. Yousaf, PIEAS
Function Terminologies
• Function prototype
• Function definition
– Function header
• Calling a function
• Passing arguments
• Returning a value
Dr. Yousaf, PIEAS
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1 = 10, num2 = 20, add_result;
add_result = addnumbers(num1,
num2);
printf(“Result is %dn",add_result);
getchar(); return 0;
}
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Function Prototype
Dr. Yousaf, PIEAS
// Addition of two integers using
Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
• A function prototype means to declare the function
(as you declare a variable prior to use)
• A prototype tells your C program what to expect
from a function - what arguments it takes (if any) and
what it returns (if any)
• Prototypes should go before main()
• A function MUST return the variable type we say that
it does in the prototype.
• #include finds the prototypes for library
functions (e.g. printf)
Dr. Yousaf, PIEAS
Function Prototype
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after
use in program
– The function with the prototype
int maximum( int, char, float );
• Takes in 1 int, 1 char, and 1 float
• Returns an int
Dr. Yousaf, PIEAS
Function Prototype
Function Definition
Dr. Yousaf, PIEAS
// Addition of two integers using
Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Function Header
Dr. Yousaf, PIEAS
// Addition of two integers using
Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
/* The first line of the
function definition (as
shown in blue color
above) is called Function
Header. */
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter
unless, the parameter is of type int
• The word int preceding the function name indicates
that this particular function has a return value of type
int.
Dr. Yousaf, PIEAS
Function Definition
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks
• Functions can not be defined inside other functions
Dr. Yousaf, PIEAS
Function Definition
Invoking a Function
• Invoking a function means calling a function to use
it.
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
• Function call analogy:
• Boss asks worker to complete task
–Worker gets information, does task, returns
result
–Information hiding: boss does not know
details
Dr. Yousaf, PIEAS
• The function is called (or invoked, or executed) to do its
job:
• Format for calling functions
VariableToStoreReturnValue = FunctionName( argument );
• If multiple arguments, use comma-separated list
– Arguments may be constants, variables, or
expressions
Dr. Yousaf, PIEAS
Invoking a Function
Arguments
• An argument is the input to the function; it is placed
inside the parentheses following the function name.
• The function then processes the argument and
returns a value; this is the output from the function.
• An argument is a piece of data (an int value, for
example) passed from a program to the function.
• Arguments allow a function to operate with different
values.
Dr. Yousaf, PIEAS
Returning a Value
• To return a value from a C function you must
explicitly return it with a return statement.
• Syntax:
• return x; // value of x will be returned
• return <expression>; // value of the
expression will be returned. e.g. return x+10
The expression can be any valid C expression that
resolves to the type defined in the function header.
Dr. Yousaf, PIEAS
– Returning control
• If nothing returned
–return;
–or, until reaches right brace
• If something returned
–return expression;
Dr. Yousaf, PIEAS
Returning a Value
Notes About Functions
There can be following forms of a functions
A. Function with no return values and no arguments
void func();
B. Functions with arguments with no return value
void func(int x, inty);
C. Functions with return value with no arguments
int func();
D. Functions with return value and arguments
float func(float x, char c);
…………………………………………………………………………………
int add(int ,int );/*Prototype , parameter type is specified
only , Parameter names are not necessary here */
Dr. Yousaf, PIEAS
• Function Prototype Examples
double squared (double number);
void print_report (int);
int get_menu_choice (void);
• Function Definition Examples
double squared (double number)
{
return (number * number);
}
void print_report (int report_number)
{
if (report_nmber == 1)
printf(“Printer Report 1”);
else
printf(“Not printing Report 1”);
}
Dr. Yousaf, PIEAS
Some Examples
• int get_menu_choice (void);
void parameter list means it takes no parameters
• void print_report (int);
return type void means it returns nothing
Dr. Yousaf, PIEAS
Some Examples
An example of function
#include <stdio.h>
int maximum (int, int);
int main()
{
int i= 4;
int j= 5;
int k;
k= maximum (i,j); /* Call maximum function */
printf ("%d is the largest from %d and %dn",k,i,j);
getchar();
return 0;
}
int maximum (int a, int b)
/* Return the largest integer */
{
if (a > b)
return a; /* Return means "I am the result of the function"*/
return b; /* exit the function with this result */
}
Prototype the function
Call the function
The function itself
function header
Dr. Yousaf, PIEAS
Syntax
• Function Prototype:
return_type function_name (type1 name1, type2
name2, ..., typen namen);
• Function Definition:
return_type function_name (type1 name1, type2 name2,
...,typen namen)
{
....statements...
}
Dr. Yousaf, PIEAS
Notes about functions
• A function can take any number of arguments
mixed in any way.
• At this stage, we are dealing with a function that
can return at most one argument.
• We can declare variables within a function just
like we can within main() - these variables will
“reset”, when we return from the function
Dr. Yousaf, PIEAS
Where do functions go in the program
• It is common to make main() the first function in
your code.
• A usual order is: Prototypes THEN main THEN other
functions.
• Prototypes must come before functions are used.
Dr. Yousaf, PIEAS
void functions
• A function doesn't necessarily have to take or
return arguments. We prototype such a function
using void.
void print_hello (void);
Main Program Here
void print_hello (void)
// this function prints hello
{
printf ("Hellon");
}
Prototype
Function takes no arguments
and returns void
Dr. Yousaf, PIEAS
void functions
void odd_or_even (int num)
/* this function prints odd or even
appropriately */
{
if ((num % 2) == 0) {
printf ("Evenn");
return;
}
printf ("Oddn");
}
void odd_or_even (int);
Main program here
Function which takes one
int arguments and returns none
Another prototype
Dr. Yousaf, PIEAS
Different Function Components in
one Look
Dr. Yousaf, PIEAS
Eliminating the Prototype
Dr. Yousaf, PIEAS
// Addition of two integers using
Function
#include<stdio.h>
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result =
addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar();
return 0;
}

More Related Content

What's hot

Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 

What's hot (20)

Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Function
FunctionFunction
Function
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Open Machine Learning
Open Machine LearningOpen Machine Learning
Open Machine Learning
 
Python advance
Python advancePython advance
Python advance
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Python programming
Python  programmingPython  programming
Python programming
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
 
08 -functions
08  -functions08  -functions
08 -functions
 

Similar to C Language Lecture 15

Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 

Similar to C Language Lecture 15 (20)

Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
Function
Function Function
Function
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Function
FunctionFunction
Function
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Functions
Functions Functions
Functions
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
Functions
FunctionsFunctions
Functions
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
C function
C functionC function
C function
 
Unit 8
Unit 8Unit 8
Unit 8
 
Functions in c
Functions in cFunctions in c
Functions in c
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (20)

C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
C Language Lecture 20
C Language Lecture 20C Language Lecture 20
C Language Lecture 20
 
C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 11
C Language Lecture  11C Language Lecture  11
C Language Lecture 11
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
C Language Lecture 9
C Language Lecture 9C Language Lecture 9
C Language Lecture 9
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C Language Lecture 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Recently uploaded (20)

UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS Publications
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 

C Language Lecture 15

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 3. // Addition of two integers without Function #include<stdio.h> int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = num1 + num2; printf("Addition result is %dn",add_result); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 4. // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; } Dr. Yousaf, PIEAS
  • 5. • The function is one of the most important topic to understand in C programming. • A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked (called) from other parts of the program. • A function is a sub-unit of a program which performs a specific task. • Functions are modules in c. • Functions take arguments (constants values or variables) and may return a value. Dr. Yousaf, PIEAS Functions
  • 6. Benefits of Functions • Benefits of functions – Divide and conquer • Construct a program from smaller pieces or components • Modularize a program (These smaller pieces are called modules) • Each piece more manageable than the original program • Manageable program development – Software reusability • Use existing functions as building blocks for new programs • Abstraction - hide internal details (library functions) – Avoid code repetition Dr. Yousaf, PIEAS
  • 7. • The most important reason to use functions is to aid in the conceptual organization of a program. Dividing a program into functions is, one of the major principles of structured programming. • Another reason to use functions is to reduce program size. • The function’s code is stored in only one place in memory, even though the function is executed many times in the course of the program. Dr. Yousaf, PIEAS Benefits of Functions
  • 8. Functions • A function receives zero or more parameters, performs a specific task, and returns none or one value. • A function is invoked by its name and parameters. – No two functions have the same name in your C program. – The communication between the function and invoker is through the parameters and the return value. • A function is independent. – It is “completely” self-contained. – It can be called at any places of your code. • Functions make programs reusable and readable. Dr. Yousaf, PIEAS
  • 9. • We have already used functions from the C library – printf(), gets(), scanf(), strcpy etc. • We need to learn to write our own functions • Programs combine user-defined functions with library functions • C standard library has a wide variety of functions Dr. Yousaf, PIEAS Functions
  • 11. Function Terminologies • Function prototype • Function definition – Function header • Calling a function • Passing arguments • Returning a value Dr. Yousaf, PIEAS #include<stdio.h> int addnumbers(int x, int y); int main() { int num1 = 10, num2 = 20, add_result; add_result = addnumbers(num1, num2); printf(“Result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; }
  • 12. Function Prototype Dr. Yousaf, PIEAS // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; }
  • 13. • A function prototype means to declare the function (as you declare a variable prior to use) • A prototype tells your C program what to expect from a function - what arguments it takes (if any) and what it returns (if any) • Prototypes should go before main() • A function MUST return the variable type we say that it does in the prototype. • #include finds the prototypes for library functions (e.g. printf) Dr. Yousaf, PIEAS Function Prototype
  • 14. • Function prototype – Function name – Parameters – what the function takes in – Return type – data type function returns (default int) – Used to validate functions – Prototype only needed if function definition comes after use in program – The function with the prototype int maximum( int, char, float ); • Takes in 1 int, 1 char, and 1 float • Returns an int Dr. Yousaf, PIEAS Function Prototype
  • 15. Function Definition Dr. Yousaf, PIEAS // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; }
  • 16. Function Header Dr. Yousaf, PIEAS // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; } /* The first line of the function definition (as shown in blue color above) is called Function Header. */
  • 17. • Function definition format return-value-type function-name( parameter-list ) { declarations and statements } – Function-name: any valid identifier – Return-value-type: data type of the result (default int) • void – indicates that the function returns nothing – Parameter-list: comma separated list, declares parameters • A type must be listed explicitly for each parameter unless, the parameter is of type int • The word int preceding the function name indicates that this particular function has a return value of type int. Dr. Yousaf, PIEAS Function Definition
  • 18. • Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } – Declarations and statements: function body (block) • Variables can be declared inside blocks • Functions can not be defined inside other functions Dr. Yousaf, PIEAS Function Definition
  • 19. Invoking a Function • Invoking a function means calling a function to use it. • Provide function name and arguments (data) • Function performs operations or manipulations • Function returns results • Function call analogy: • Boss asks worker to complete task –Worker gets information, does task, returns result –Information hiding: boss does not know details Dr. Yousaf, PIEAS
  • 20. • The function is called (or invoked, or executed) to do its job: • Format for calling functions VariableToStoreReturnValue = FunctionName( argument ); • If multiple arguments, use comma-separated list – Arguments may be constants, variables, or expressions Dr. Yousaf, PIEAS Invoking a Function
  • 21. Arguments • An argument is the input to the function; it is placed inside the parentheses following the function name. • The function then processes the argument and returns a value; this is the output from the function. • An argument is a piece of data (an int value, for example) passed from a program to the function. • Arguments allow a function to operate with different values. Dr. Yousaf, PIEAS
  • 22. Returning a Value • To return a value from a C function you must explicitly return it with a return statement. • Syntax: • return x; // value of x will be returned • return <expression>; // value of the expression will be returned. e.g. return x+10 The expression can be any valid C expression that resolves to the type defined in the function header. Dr. Yousaf, PIEAS
  • 23. – Returning control • If nothing returned –return; –or, until reaches right brace • If something returned –return expression; Dr. Yousaf, PIEAS Returning a Value
  • 24. Notes About Functions There can be following forms of a functions A. Function with no return values and no arguments void func(); B. Functions with arguments with no return value void func(int x, inty); C. Functions with return value with no arguments int func(); D. Functions with return value and arguments float func(float x, char c); ………………………………………………………………………………… int add(int ,int );/*Prototype , parameter type is specified only , Parameter names are not necessary here */ Dr. Yousaf, PIEAS
  • 25. • Function Prototype Examples double squared (double number); void print_report (int); int get_menu_choice (void); • Function Definition Examples double squared (double number) { return (number * number); } void print_report (int report_number) { if (report_nmber == 1) printf(“Printer Report 1”); else printf(“Not printing Report 1”); } Dr. Yousaf, PIEAS Some Examples
  • 26. • int get_menu_choice (void); void parameter list means it takes no parameters • void print_report (int); return type void means it returns nothing Dr. Yousaf, PIEAS Some Examples
  • 27. An example of function #include <stdio.h> int maximum (int, int); int main() { int i= 4; int j= 5; int k; k= maximum (i,j); /* Call maximum function */ printf ("%d is the largest from %d and %dn",k,i,j); getchar(); return 0; } int maximum (int a, int b) /* Return the largest integer */ { if (a > b) return a; /* Return means "I am the result of the function"*/ return b; /* exit the function with this result */ } Prototype the function Call the function The function itself function header Dr. Yousaf, PIEAS
  • 28. Syntax • Function Prototype: return_type function_name (type1 name1, type2 name2, ..., typen namen); • Function Definition: return_type function_name (type1 name1, type2 name2, ...,typen namen) { ....statements... } Dr. Yousaf, PIEAS
  • 29. Notes about functions • A function can take any number of arguments mixed in any way. • At this stage, we are dealing with a function that can return at most one argument. • We can declare variables within a function just like we can within main() - these variables will “reset”, when we return from the function Dr. Yousaf, PIEAS
  • 30. Where do functions go in the program • It is common to make main() the first function in your code. • A usual order is: Prototypes THEN main THEN other functions. • Prototypes must come before functions are used. Dr. Yousaf, PIEAS
  • 31. void functions • A function doesn't necessarily have to take or return arguments. We prototype such a function using void. void print_hello (void); Main Program Here void print_hello (void) // this function prints hello { printf ("Hellon"); } Prototype Function takes no arguments and returns void Dr. Yousaf, PIEAS
  • 32. void functions void odd_or_even (int num) /* this function prints odd or even appropriately */ { if ((num % 2) == 0) { printf ("Evenn"); return; } printf ("Oddn"); } void odd_or_even (int); Main program here Function which takes one int arguments and returns none Another prototype Dr. Yousaf, PIEAS
  • 33. Different Function Components in one Look Dr. Yousaf, PIEAS
  • 34. Eliminating the Prototype Dr. Yousaf, PIEAS // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y) { int z; z = x +y; return z; } int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; }