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

Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 

What's hot (20)

Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Nested loops
Nested loopsNested loops
Nested loops
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
C string
C stringC string
C string
 
Function
FunctionFunction
Function
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Strings in C
Strings in CStrings in C
Strings in C
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
String functions in C
String functions in CString functions in C
String functions in C
 

Similar to Programming Fundamentals Functions in C and types

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 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
 
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
 
Function in c program
Function in c programFunction in c program
Function in c program
 
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

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

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 

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