SlideShare a Scribd company logo
1 of 52
Download to read offline
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from
functions
• Preprocessor directives
• Local and external variables
C Functions
• A function is used to perform a specific task. It groups a number of
program statements into a unit and gives it a name.
• Once defined a function can be called from other parts of the program
Advantages of Using Functions
1) Program structure/organization
becomes simpler/easy
to
understand
2) Functions reduce the size of
the program and consequently
memory:
1) Any sequence of instructions that
appears in a program more than
once is a candidate for being
made into a function.
2) 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.
Function Example
#include <stdio.h>
#include <conio.h>
Write a function that adds two numbers: void add();
Output: int main()
{ addition of num1 and num2 is: 20 printf("addition of num1 and num2 is: “);
add(); getch();
}
void add()
{
int num1, num2, sum;
num1 = 5; num2 = 15;
sum = num1 + num2;
printf(“%d”, sum);
}
#include <stdio.h>
#include <conio.h>
void add();
Function Example
int main()
{
printf("addition of num1 and num2 is: “);
add();
getch(); }
void add()
{
int num1, num2, sum;
num1 = 5; num2 = 15;
sum = num1 + num2; printf(“%d”, sum);
}
There are three (03) necessary components of a function:
1) Function declaration (Prototype)
2) Calls to the Function
3) Function definition
Function Example
#include <stdio.h>
void add();
int main()
{
printf "addition( of num1 and num2 is: “);
add();
getch();
}
void add()
{
int num1, num2, sum;
num1 = 5;
num2 = 15;
sum = num1 + num2;
printf(“%d”,sum);
}
The declarator must agree with the
declaration: It must use the same
function name, have the same
argument types in the same order (if
there are arguments), and have the
same return type.
Function Example
#include <conio.h>
Summary: Function Components
Comparison With Library Functions
• The declaration of library function such as getche() or getch()
lies within the header file conio.h and the definition of library
Call Causes the function to be executed func();
function is in a library file that’s linked automatically to your
program when you build it.
• However, for user-defined function declaration and definition
are written explicitly as part of source program.
L
ibrary Functions
10
Exercise
• Write a function that computes and prints the
area of a rectangle (area=length*width).
Class Assignment
Write a program using functions that generates the following output (Note:
number of stars in each line is 40):
****************************************
COMPUTER SCIENCE DEPARTMENT
****************************************
NAME: MUHAMMAD FAISAL
CLASS: 18BCS
ROLL NUMBER: 100
****************************************
Class Assignment: Answer
#include <stdio.h>
#include <conio.h>
void starline();
int main()
{
starline();
printf (“COMPUTER SCIENCE DEPARTMENT: n“);
starline();
printf("NAME: MUHAMMAD FAISAL : “);
printf(“CLASS : 18BCSn “);
printf("ROLL NR. 100 “);
starline();
getch();
}
void starline()
{
for(int j=1; j<=40; j++)
printf("*“);
printf(“n”);
}
Passing Arguments To Functions
• Argument: is a piece of data (an int value, for example)
passed from main program to the function.
• There are mainly two (02) ways arguments can be
passed from the main program to the function:
1) Passing constants
2) Passing variables
– Pass by value
– Pass by reference
Simple Function
#include <stdio.h>
#include <conio.h>
void starline();
int main()
{
starline();
printf (“COMPUTER SCIENCE DEPARTMENT: n“);
starline();
printf("NAME: MUHAMMAD FAISAL : n“);
printf(“CLASS : 18BCSn “);
printf("ROLL NR. 100 “);
starline();
getch();
}
void starline()
{
for(int j=1; j<=40; j++)
printf("*“);
printf(“n”);
}
How about this output with starline()?
****************************************
COMPUTER SCIENCE DEPARTMENT
========================================
NAME: MUHAMMAD FAISAL
CLASS: 18BCS
ROLL NUMBER: 100
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#include <stdio.h>
#include <conio.h> 1) Passing Constants
void starline(char , int );
int main()
{
starline('*', 40);
printf(“COMPUTER SCIENCE DEPTARTMENT.: n" );
starline(‘=', 40);
printf(“NAME: MUHAMMAD FAISAL : n“);
printf(“CLASS: 18BCS n”);
printf("ROLL NR. 100 n”);
starline(‘%', 40);
getch();
}
void starline(char ch, int n)
{
for(int j=1; j<=n; j++)
printf(“%c”,ch);
printf(“n”);
}
#include <stdio.h>
#include <conio.h> 2) Passing Variables
void starline(char , int ); Instead of constants, main program can also pass
variables to the function int main() being called.
{
starline('*', 40);
printf(“COMPUTER SCIENCE DEPTARTMENT.: n" );
starline(‘=', 40);
printf(“NAME: MUHAMMAD FAISAL : n“);
printf(“CLASS: 18BCS n”);
printf("ROLL NR. 100 n”);
starline(‘%', 40);
getch();
}
void starline(char ch, int n)
{
for(int j=1; j<=n; j++)
printf(“%c”,ch);
printf(“n”);
}
void starline(char , int );
2) Passing Variables
int
main()
printf(“Enter a character and a number: n”);
scanf(“%c%d”,&chin,&nin);
starline(chin, nin);
{
char chin;
int nin;
Instead of constants, main program
can also pass variables to the function
to being called.
printf(“COMPUTER SCIENCE DEPTARTMENT: n“);
starline(chin, nin);
printf("NAME: MUAHAMMAD FAISAL: n“);
printf(“CLASS: 18BCS n“);
printf("ROLL NR. 100 n“);
starline(chin, nin);
getch();
}
void starline(char ch, int n)
{
for(int j=1; j<=n; j++)
printf(“%c”, ch);
printf(“n”); }
Exercise
• Write a function that prints the ages of
students in bar graph as given below:
Passing by Value
• When the main program calls a
function (e.g., starline(chin,nin)),
the values of variables are passed
to the called function.
• In this case, the called function
creates new variables to hold the
values for these variable
arguments:
• The function gives these new variables the
names and data types of the parameters
specified in the declarator: ch of type char
and n of type int.
• Passing arguments in this way,
where the function creates copies
This statement in main
causes the values in
these variable to be
copied into these
parameters
starline(chin, nin);
starline(char ch, int n);
of the arguments passed to it, is
called passing by values.
Exercise: What is the output?
#include <stdio.h>
#include <conio.h>
int num1 = 7, num2 = 5;
duplicate(num1, num2); printf("num1 = %d
num2 is = %d”, num1,num2);
void duplicate(int, int);
int main()
{
void duplicate(int n1, int n2)
{
n1 += 2;
n2 *= 3;
}
getch();
}
Exercises
• Write a function that gets integer number
from the user and finds whether the input
number is odd or even.
• Write a function that distinguishes negative
and positive input number.
Assignment: Calculator
Write a program for calculator that performs
simple calculations: Add, Subtract, Multiply,
and Divide. (HINT: You may use switch or
else-if construct for implementing
calculator.)
For keeners: Fine tune your calculator with
other operations like square, power, square
root and so on.
Returning Values From Functions
• When a function completes its execution, it can return a single value to the
main program.
• Usually this return value consists of an answer to the problem the function has
solved.
• The value returned by the function can be of type (int, float, double) and must
match the return type in the declarator.
float km_into_m(float);
int main() {
float km, m;
printf(“Enter value for kilo meter: ”);
scanf(“%f”, &km);
m = km_into_m(km);
printf(“km into m are: %f”, m);
getch(); }
float km_into_m(float kilometers)
{
int meters;
meters = kilometers * 1000;
return meters;
}
• If it is required to output/print a value from the main program then return that
value from the called function rather then printing from it.
• Notice that main function does not access variable “meters” in function, but it
receives the value and then stores in its own variable, “m” in this case.
Exercises
• Write a function that calculates and returns the
area of a circle to the main program
(Area= Pi r2)
Limitations of return() statement
Using more than one function
Using more than one function
Recursion
• Recursion is a programming technique by which a
function calls itself.
• Russian Dolls:
• Tower of Hanoi:
Recursion: Factorial of a Number
#include <stdio.h>
#include <conio.h>
long factfunc(long n)
long factfunc(long);
{
if(n == 0)
int main() return 1;
{ else
long n; return n * factfunc(n-1);
long fact;
}
printf("Enter a number: ");
scanf("%d“, &n);
fact = factfunc(n);
printf("Factorial of %d is %d", n,fact);
getch();
}
Preprocessor Directives
• Program statements are instructions to the
computer to perform some task.
• Preprocessor directives are the instruction to
the compiler itself.
• Rather than being translated to the machine
language, preprocessor directives are
operated directly by the compiler before the
computation process even starts; hence called
preprocessor.
Preprocessor Directives
The #define Directive
The #define Directive
The #define Directive
Why use #define Directive
Why not use variable names instead?
Why not use variable names instead?
The const modifier
float const PI = 3.141592;
Macros
Macros
Macros: Arguments
The #include Directive
The #include Directive: Example
Save this file to myMath.c or with your own name but with .c extension.
The second step is to create myMath file with .h extension and place it
in the same folder as myMath.c
The #include Directive: Example
Variable Scope
• The scope (or visibility) of a variable describes the
locations within a program from which it can be
accessed.
OR
• The scope of a variable is that part of the program
where the variable is visible/accessible.
• Two types of variable scopes:
1) Local
2) Global/External
Variable Scope: Local
• Variables defined within/inside a function have local
scope
• Variables with local scope are only accessible within a function; any
attempt to access them from outside the function results in error
message.
Variable Scope: Local
Variable Scope: Global/External/File
• Variable defined outside all functions (and before main() function) have global
scope.
• Variables with global scope are accessible from any part of the program.
#include <stdio.h>
#include <conio.h>
void func1() int
n = 5;
{
n = n + 2; void func1(); printf(“%d”,n); void func2();
}
int
main()
{
void func2()
func1();
{ func2();
n = n * 2;
printf(“%d”,n); getch();
}
}

More Related Content

What's hot (20)

Function in C
Function in CFunction in C
Function in C
 
functions of C++
functions of C++functions of C++
functions of C++
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
STORAGE CLASSES
STORAGE CLASSESSTORAGE CLASSES
STORAGE CLASSES
 
Files in C
Files in CFiles in C
Files in C
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Exception handling
Exception handlingException handling
Exception handling
 
File in C language
File in C languageFile in C language
File in C language
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Operators
OperatorsOperators
Operators
 
C string
C stringC string
C string
 

Similar to Programming Fundamentals Functions in C and types

Similar to Programming Fundamentals Functions in C and types (20)

unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
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
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Functions
FunctionsFunctions
Functions
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
C function
C functionC function
C function
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Lecture6
Lecture6Lecture6
Lecture6
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
5. Functions in C.pdf
5. Functions in C.pdf5. Functions in C.pdf
5. Functions in C.pdf
 
Presentation on C language By Kirtika thakur
Presentation on C language By Kirtika thakurPresentation on C language By Kirtika thakur
Presentation on C language By Kirtika thakur
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Functions
Functions Functions
Functions
 

More from imtiazalijoono

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programmingimtiazalijoono
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripheralsimtiazalijoono
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.imtiazalijoono
 
Negative amplifiers and its types Positive feedback and Negative feedback
Negative amplifiers and its types Positive feedback  and Negative feedbackNegative amplifiers and its types Positive feedback  and Negative feedback
Negative amplifiers and its types Positive feedback and Negative feedbackimtiazalijoono
 
Multistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierMultistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierimtiazalijoono
 
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...imtiazalijoono
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge imtiazalijoono
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development processimtiazalijoono
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts TranslatorsProgramming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts Translatorsimtiazalijoono
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Conceptsimtiazalijoono
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variableimtiazalijoono
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayimtiazalijoono
 
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,imtiazalijoono
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsimtiazalijoono
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGimtiazalijoono
 

More from imtiazalijoono (20)

Embedded systems io programming
Embedded systems   io programmingEmbedded systems   io programming
Embedded systems io programming
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
 
Importance of reading and its types.
Importance of reading and its types.Importance of reading and its types.
Importance of reading and its types.
 
Negative amplifiers and its types Positive feedback and Negative feedback
Negative amplifiers and its types Positive feedback  and Negative feedbackNegative amplifiers and its types Positive feedback  and Negative feedback
Negative amplifiers and its types Positive feedback and Negative feedback
 
Multistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifierMultistage amplifiers and Name of coupling Name of multistage amplifier
Multistage amplifiers and Name of coupling Name of multistage amplifier
 
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...Loop Introduction for Loop  while Loop do while Loop  Nested Loops  Values of...
Loop Introduction for Loop while Loop do while Loop Nested Loops Values of...
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
 
Software Development Software development process
Software Development Software development processSoftware Development Software development process
Software Development Software development process
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Programming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts TranslatorsProgramming Fundamentals and Programming Languages Concepts Translators
Programming Fundamentals and Programming Languages Concepts Translators
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
 
Programming Global variable
Programming Global variableProgramming Global variable
Programming Global variable
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
 
Arithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operatorsArithmetic and Arithmetic assignment operators
Arithmetic and Arithmetic assignment operators
 
INTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMINGINTRODUCTION TO COMPUTER PROGRAMMING
INTRODUCTION TO COMPUTER PROGRAMMING
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
 
COMPUTER PROGRAMMING
COMPUTER PROGRAMMINGCOMPUTER PROGRAMMING
COMPUTER PROGRAMMING
 

Recently uploaded

Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Mark Carrigan
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTechSoup
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17Celine George
 
Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024CapitolTechU
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Celine George
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resourcesaileywriter
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxJenilouCasareno
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
factors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxfactors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxSanjay Shekar
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptxmansk2
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya - UEM Kolkata Quiz Club
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxnuriaiuzzolino1
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxCapitolTechU
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17Celine George
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff17thcssbs2
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxjmorse8
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdfVikramadityaRaj
 
Essential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonEssential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonMayur Khatri
 

Recently uploaded (20)

Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17
 
Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdfPost Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
factors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxfactors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptx
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptx
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Essential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonEssential Safety precautions during monsoon season
Essential Safety precautions during monsoon season
 

Programming Fundamentals Functions in C and types

  • 2. Lecture Outline • Functions • Function declaration • Function call • Function definition
  • 3. – Passing arguments to function 1) Passing constants 2) Passing variables – Pass by value – Returning values from functions • Preprocessor directives • Local and external variables C Functions • A function is used to perform a specific task. It groups a number of program statements into a unit and gives it a name.
  • 4. • Once defined a function can be called from other parts of the program Advantages of Using Functions
  • 5. 1) Program structure/organization becomes simpler/easy to understand 2) Functions reduce the size of the program and consequently memory: 1) Any sequence of instructions that appears in a program more than once is a candidate for being made into a function. 2) 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.
  • 6. Function Example #include <stdio.h> #include <conio.h> Write a function that adds two numbers: void add(); Output: int main() { addition of num1 and num2 is: 20 printf("addition of num1 and num2 is: “); add(); getch(); } void add() { int num1, num2, sum; num1 = 5; num2 = 15; sum = num1 + num2; printf(“%d”, sum); } #include <stdio.h> #include <conio.h> void add();
  • 7. Function Example int main() { printf("addition of num1 and num2 is: “); add(); getch(); } void add() { int num1, num2, sum; num1 = 5; num2 = 15; sum = num1 + num2; printf(“%d”, sum); } There are three (03) necessary components of a function: 1) Function declaration (Prototype) 2) Calls to the Function 3) Function definition
  • 8. Function Example #include <stdio.h> void add(); int main() { printf "addition( of num1 and num2 is: “); add(); getch(); } void add() { int num1, num2, sum; num1 = 5; num2 = 15; sum = num1 + num2; printf(“%d”,sum); } The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type.
  • 10. Summary: Function Components Comparison With Library Functions • The declaration of library function such as getche() or getch() lies within the header file conio.h and the definition of library Call Causes the function to be executed func();
  • 11. function is in a library file that’s linked automatically to your program when you build it. • However, for user-defined function declaration and definition are written explicitly as part of source program.
  • 12. L
  • 14. Exercise • Write a function that computes and prints the area of a rectangle (area=length*width).
  • 15. Class Assignment Write a program using functions that generates the following output (Note: number of stars in each line is 40): **************************************** COMPUTER SCIENCE DEPARTMENT **************************************** NAME: MUHAMMAD FAISAL CLASS: 18BCS ROLL NUMBER: 100 **************************************** Class Assignment: Answer #include <stdio.h>
  • 16. #include <conio.h> void starline(); int main() { starline(); printf (“COMPUTER SCIENCE DEPARTMENT: n“); starline(); printf("NAME: MUHAMMAD FAISAL : “); printf(“CLASS : 18BCSn “); printf("ROLL NR. 100 “); starline(); getch(); } void starline() { for(int j=1; j<=40; j++) printf("*“); printf(“n”);
  • 17. } Passing Arguments To Functions • Argument: is a piece of data (an int value, for example) passed from main program to the function. • There are mainly two (02) ways arguments can be passed from the main program to the function: 1) Passing constants 2) Passing variables – Pass by value – Pass by reference
  • 18. Simple Function #include <stdio.h> #include <conio.h> void starline(); int main() { starline(); printf (“COMPUTER SCIENCE DEPARTMENT: n“); starline(); printf("NAME: MUHAMMAD FAISAL : n“); printf(“CLASS : 18BCSn “); printf("ROLL NR. 100 “); starline(); getch(); } void starline() {
  • 19. for(int j=1; j<=40; j++) printf("*“); printf(“n”); } How about this output with starline()? **************************************** COMPUTER SCIENCE DEPARTMENT ======================================== NAME: MUHAMMAD FAISAL CLASS: 18BCS ROLL NUMBER: 100 %%%%%%%%%%%%%%%%%%%%%%%%%%%% #include <stdio.h>
  • 20. #include <conio.h> 1) Passing Constants void starline(char , int ); int main() { starline('*', 40); printf(“COMPUTER SCIENCE DEPTARTMENT.: n" ); starline(‘=', 40); printf(“NAME: MUHAMMAD FAISAL : n“); printf(“CLASS: 18BCS n”); printf("ROLL NR. 100 n”); starline(‘%', 40); getch(); } void starline(char ch, int n) {
  • 21. for(int j=1; j<=n; j++) printf(“%c”,ch); printf(“n”); } #include <stdio.h> #include <conio.h> 2) Passing Variables void starline(char , int ); Instead of constants, main program can also pass variables to the function int main() being called. { starline('*', 40); printf(“COMPUTER SCIENCE DEPTARTMENT.: n" ); starline(‘=', 40); printf(“NAME: MUHAMMAD FAISAL : n“); printf(“CLASS: 18BCS n”); printf("ROLL NR. 100 n”); starline(‘%', 40); getch();
  • 22. } void starline(char ch, int n) { for(int j=1; j<=n; j++) printf(“%c”,ch); printf(“n”); } void starline(char , int ); 2) Passing Variables int main() printf(“Enter a character and a number: n”); scanf(“%c%d”,&chin,&nin); starline(chin, nin); { char chin; int nin; Instead of constants, main program can also pass variables to the function to being called.
  • 23. printf(“COMPUTER SCIENCE DEPTARTMENT: n“); starline(chin, nin); printf("NAME: MUAHAMMAD FAISAL: n“); printf(“CLASS: 18BCS n“); printf("ROLL NR. 100 n“); starline(chin, nin); getch(); } void starline(char ch, int n) { for(int j=1; j<=n; j++) printf(“%c”, ch); printf(“n”); } Exercise • Write a function that prints the ages of students in bar graph as given below:
  • 24.
  • 25. Passing by Value • When the main program calls a function (e.g., starline(chin,nin)), the values of variables are passed to the called function. • In this case, the called function creates new variables to hold the values for these variable arguments: • The function gives these new variables the names and data types of the parameters specified in the declarator: ch of type char and n of type int. • Passing arguments in this way, where the function creates copies This statement in main causes the values in these variable to be copied into these parameters starline(chin, nin); starline(char ch, int n);
  • 26. of the arguments passed to it, is called passing by values. Exercise: What is the output? #include <stdio.h> #include <conio.h> int num1 = 7, num2 = 5; duplicate(num1, num2); printf("num1 = %d num2 is = %d”, num1,num2); void duplicate(int, int); int main() { void duplicate(int n1, int n2) { n1 += 2; n2 *= 3; }
  • 27. getch(); } Exercises • Write a function that gets integer number from the user and finds whether the input number is odd or even. • Write a function that distinguishes negative and positive input number.
  • 28. Assignment: Calculator Write a program for calculator that performs simple calculations: Add, Subtract, Multiply, and Divide. (HINT: You may use switch or else-if construct for implementing calculator.) For keeners: Fine tune your calculator with other operations like square, power, square root and so on.
  • 29. Returning Values From Functions • When a function completes its execution, it can return a single value to the main program. • Usually this return value consists of an answer to the problem the function has solved. • The value returned by the function can be of type (int, float, double) and must match the return type in the declarator. float km_into_m(float); int main() { float km, m; printf(“Enter value for kilo meter: ”); scanf(“%f”, &km); m = km_into_m(km); printf(“km into m are: %f”, m); getch(); } float km_into_m(float kilometers) { int meters; meters = kilometers * 1000; return meters; } • If it is required to output/print a value from the main program then return that value from the called function rather then printing from it.
  • 30. • Notice that main function does not access variable “meters” in function, but it receives the value and then stores in its own variable, “m” in this case. Exercises • Write a function that calculates and returns the area of a circle to the main program (Area= Pi r2) Limitations of return() statement
  • 31. Using more than one function
  • 32. Using more than one function
  • 33. Recursion • Recursion is a programming technique by which a function calls itself. • Russian Dolls: • Tower of Hanoi:
  • 34. Recursion: Factorial of a Number #include <stdio.h> #include <conio.h> long factfunc(long n) long factfunc(long); { if(n == 0) int main() return 1; { else long n; return n * factfunc(n-1); long fact; } printf("Enter a number: "); scanf("%d“, &n); fact = factfunc(n);
  • 35. printf("Factorial of %d is %d", n,fact); getch(); } Preprocessor Directives • Program statements are instructions to the computer to perform some task. • Preprocessor directives are the instruction to the compiler itself. • Rather than being translated to the machine language, preprocessor directives are operated directly by the compiler before the
  • 36. computation process even starts; hence called preprocessor. Preprocessor Directives
  • 40. Why use #define Directive Why not use variable names instead?
  • 41. Why not use variable names instead?
  • 42. The const modifier float const PI = 3.141592;
  • 47. The #include Directive: Example Save this file to myMath.c or with your own name but with .c extension. The second step is to create myMath file with .h extension and place it in the same folder as myMath.c
  • 48. The #include Directive: Example Variable Scope • The scope (or visibility) of a variable describes the locations within a program from which it can be accessed.
  • 49. OR • The scope of a variable is that part of the program where the variable is visible/accessible. • Two types of variable scopes: 1) Local 2) Global/External Variable Scope: Local • Variables defined within/inside a function have local scope • Variables with local scope are only accessible within a function; any attempt to access them from outside the function results in error message.
  • 50.
  • 51. Variable Scope: Local Variable Scope: Global/External/File • Variable defined outside all functions (and before main() function) have global scope. • Variables with global scope are accessible from any part of the program.
  • 52. #include <stdio.h> #include <conio.h> void func1() int n = 5; { n = n + 2; void func1(); printf(“%d”,n); void func2(); } int main() { void func2() func1(); { func2(); n = n * 2; printf(“%d”,n); getch(); } }