Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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:
Programming Fundamentals  Functions in C  and types
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.
Programming Fundamentals  Functions in C  and types
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

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