Cfunc

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Computer Programming

Functions in C
C Functions
• A function is a group of statements that together perform a task.
• A function groups a number of program statements into a unit and
gives it a name.
void starline()
{
for(int j=0; j<45; j++)
printf(“* ”);
}

• Once defined a function can be called from other parts of the program

Printf(“Welcome to 15 BS(CS): ”);

}
Functions

Function:
The strength of C language is to define and use function.
The strength of C language is that C function are easy to define and
use.
Function

Library User define


function function
Library function:
The library functions are not required to be written
by us.
Eg:
printf
scanf
User define function:
This function as to be developed by the user at the time of
writing a program.

Eg: main()

‘main’ is specially used function in C. Ever program must


have main function to indicate, where the program begins its
execution.
Library Function Example
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int num;
printf("Enter any number ");
scanf("%d",&num);
int result=sqrt(num);
printf("\nThe square root of the number is %d",result);
getch();
}
Library Function Example
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float num,pw;
printf("Enter any number");
scanf("%f",&num);
printf("Enter power of the number ");
scanf("%f",&pw);
float result=pow(num,pw);
printf("\nThe power of the number is %f", result);
getch();
}
User Defined Function Example
#include <stdio.h>
#include <conio.h> There are three (03) necessary components of a function:

void add(); 1) Function declaration


2) Calls to the Function
int main() 3) Function definition
{
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> Function Example
#include<conio.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.
Summary: Function Components

Call Causes the function to be executed func();


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.
Comparison With Library Functions
• The declaration of library function such as getche() or getch()
lies within the header files conio.h in this case, and the
definition (compiled into executable code) of library 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.
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: Zahid
Batch: 15BCS
Subject: ICP
****************************************
#include<stdio.h>
#include<conio.h> Class Assignment: Answer
void printline();

int main()
{
printline();
printf("\tComputer Science Department");
printline();
printf("\t Name: \tZahid\n");
printf("\t Batch: \t15BSCS\n");
printf("\t Subject: \tICP");
printline();
getch();
}
void printline()
{
int i;
printf("\n");
for(i=0;i<40;i++)
{ printf("*"); }
printf("\n");
}
Passing Arguments To Functions
• Argument: is a piece of data (an int value, for
example) passed from a program to the function.

• There are three ways arguments can be passed from


the main program to the function:
1) Passing constants
2) Passing variables
3) Pass by value
#include<stdio.h>
#include<conio.h> Simple Function
void printline();

int main()
{
printline();
printf("\tComputer Science Department");
printline();
printf("\t Name: \tZahid\n");
printf("\t Batch: \t15BSCS\n");
printf("\t Subject: \tICP");
printline();
getch();
}
void printline()
{
int i;
printf("\n");
for(i=0;i<40;i++)
{ printf("*"); }
printf("\n");
}
#include<stdio.h>
#include<conio.h> 1) Passing Constants
void printline(char,int);

int main()
{
printline('=', 40);
printf("\tInformation Technology Department");
printline('*', 40);
printf("\t Name: \tTuchkuly\n");
printf("\t Batch: \t17BS(IT)\n");
printf("\t Subject: \tProgramming Fundamentals");
printline('%', 40);
getch();
}
void printline(char ch,int n)
{
int i;
printf("\n");
for(i=0;i<n;i++)
{ printf("%c",ch); }
printf("\n");
}
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.
Assignment

Write a program that takes any number


from user and return its square and cube.
Hint: Use functions
void printline(char,int);
int main() 2) Passing Variables
{
char chin; Instead of constants, main function
int nin; can also pass variables to the function
printf("Enter a character and a number "); to be called.
scanf("%c %d",&chin,&nin);
printline(chin, nin);
printf("\tComputer Science Department");
printline(chin, nin);
printf("\t Name: \tZahid\n");
printf("\t Batch: \t15BSCS\n");
printf("\t Subject: \tICP");
printline(chin, nin);
getch(); }
void printline(char ch,int n)
{
int i;
printf("\n");
for(i=0;i<n;i++)
{ printf("%c",ch); }
printf("\n");
}
3) Passing by Value
• When the main program calls a starline(chin, nin);
function (e.g., starline(chin,nin)), This statement in main
the values of variables are passed causes the values in
these variable to be
to the called function. copied into these
parameters

• In this case, the called function starline(char ch, int n);


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
of the arguments passed to it, is
called passing by values.
Returning Values From Functions
• When a function completes its execution, it can return a single value to the
calling program.
• Usually this return value consists of an answer to the problem the
function has solved.
• The value returned by the called function can be of type int, float,
double and so on, matching the return type in the declarator.
float km_into_m(float);
float km_into_m(float kilometers)
int main() {
{ float km, m; int meters;
printf(“Enter value for kilo meter: ”);
scanf(“ %f ”, &km); meters = kilometers * 1000;

m = km_into_m(km); return meters;


printf(“km into m are: %f”, m); }
getch(); }
• 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 called-function,
but it receives the value and then stores in its own variable, “m” in this case.
Returning Values From Functions
• Can only a single value be returned from a function ?

• Pass by value allows a return of only one value to


the calling function.
• In order to return more than one value from a
function two techniques are used:
1) Pass by reference and
2) Structures
Pass-By-Reference
• Like pass-by-value, pass-by-reference is an other technique for
passing arguments to functions.

• When arguments are passed by-value, the called function


creates a new variable of the same type as the argument and
copies the argument’s value into it.
• Passing arguments by-value ensures that the called function cannot
access the original variable in the calling program and thus keeps
variable safe from changes.

• In pass-by-reference technique instead of a value being passed to


the function, a reference (address) to the original variable, in the
calling program, is passed.
• This also means that both calling and called function operate on the
same memory location, however, they might have different names
for using it.
Pass-By-Reference vs Pass-By-Value
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>

void duplicate(int& n1, int& n2) void duplicate(int& n1, int& n2)
{ {
n1 += 2; n1 += 2;
n2 *= 3; n2 *= 3;
} }

int main()
{ int main()
int num1 = 7, num2 = 5; {
int num1 = 7, num2 = 5;
duplicate(num1, num2);
printf("num1 = %d num2=%d “, num1,num2); duplicate(num1, num2);
printf("num1 = %d num2=%d “, num1,num2);
getch();
} getch();
}
Pass-By-Reference Swapping Numbers
#include<stdio.h> Void swap(int& numb1, int&
#include<conio.h> numb2)
void swap(int&, int&); {
int main() if(numb1>numb2)
{ {
int n1=99, n2=11; int temp=numb1;
int n3=22,n4=88; numb1=numb2;
swap(n1,n2); numb2=temp;
swap(n3,n4); }
printf("n1=%d\n",n1); }
printf("n2=%d\n",n2);
printf("n3=%d\n",n3);
printf("n4=%d",n4);
getch();
}
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.
#include<stdio.h>
#include<conio.h>
void func()
{
int a,b;
a=10;
b=20;
c=30;
}
int main()
{
int c;
a=30;
b=31;
c=32;
getch()
}
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”,n);
void func2();
}
int main()
{
void func2()
func1();
{
func2();
n = n * 2;
printf(“%d\n”,n);
getch();
}
}

You might also like