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

Types of function call
Types of function callTypes of function call
Types of function callArijitDhali
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in CMuthuganesh S
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)VC Infotech
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 

What's hot (20)

Function in c
Function in cFunction in c
Function in c
 
Types of function call
Types of function callTypes of function call
Types of function call
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Functions in C
Functions in CFunctions in C
Functions in C
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C functions
C functionsC functions
C functions
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Header files in c
Header files in cHeader files in c
Header files in c
 
C function presentation
C function presentationC function presentation
C function presentation
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 

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
 
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
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 

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

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 

Recently uploaded (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 

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