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

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional arrayRajendran
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and UnionsDhrumil Patel
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Storage class in c
Storage class in cStorage class in c
Storage class in ckash95
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++Sachin Yadav
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program Leela Koneru
 

What's hot (20)

File handling in c
File handling in cFile handling in c
File handling in c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Enums in c
Enums in cEnums in c
Enums in c
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
CONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGECONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGE
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Function in C
Function in CFunction in C
Function in C
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
structure and union
structure and unionstructure and union
structure and union
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
 

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
 
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
 
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
 
Function
FunctionFunction
Function
 
C structure
C structureC structure
C structure
 

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

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

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(); } }