You are on page 1of 43

Session Objectives

• Explain User Defined Functions


• Explain Type of Functions
• Discuss category of Functions
• Declaration & Prototypes
• Storage class in “C”
• Calling the Function
scanf()
printf() A series of Instructions
getc() that are to be executed
putc() more than once
USER DEFINED FUNCTION :
SYNTAX :
retu_datatype func_name(arguments)
{
Body of the function
statements;
return;
}

call the function from main() :


syntax :
func_name(arguments );
#include<stdio.h>
void demo() //definition
{
printf(" Welcome to functions\n");
printf("Good Morning\n");
}
void main()
{
clrscr();
printf("Main, Welcome to functions\n");
demo(); //calling
printf("Bye");
getch();
} CSC COMPUTER EDUCATION,
M.K.B.NAGAR
(Based on Return values and passing Arguments)

🖐 NO ARGUMENT NO RETURN VALUES

🖐 ARGUMENT BUT NO RETURN VALUES


🖐 NO ARGUMENT WITH RETURN VALUES
🖐 WITH ARGUMENT WITH RETURN VALUES
/* To perform Addition of two numbers */
/* NO ARGUMENT NO RETURN VALUES */
#include<stdio.h>
void add(); void add()
void main() {
{ int a,b,c;
add(); printf("Enter two numbers\n");
printf(“main ends here"); scanf("%d%d",&a,&b);
add();
getch(); c=a+b;
} printf("The sum is %d\n",c);
}
/* To perform Addition of two numbers */
/* WITH ARGUMENT BUT NO RETURN VALUES*/
#include<stdio.h>
void add(int,int);
void main()
{
int x,y;
printf("Enter two number");
scanf("\t\t%d %d",&x,&y);
add(x,y); /* Actual Arguments */
getch();
}
void add(int a,int b) /* Formal Arguments */
{
int c=a+b;
printf("\t\tThe C Value is %d",c);
}
Statement
• The return statement is used to return from a function.

• It causes execution to return to the point at which the


call to the function was made.
• The return statement can have a value with it, which it
returns to the program.
/* To perform Addition of two numbers
Without Argument and With Return values */
#include<stdio.h>
#include<conio.h>
int add(); //declaration
void main()
{
int c;
c=add(); /* Return Variable - c */
printf("The sum of two numbers is %d",c);
getch();
}
int add()
{
int a,b,c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=a+b;
return(c);
}
/* To perform Addition of two numbers
With Argument and With Return values */
#include<stdio.h>
int add(int,int); //Function prototype declaration
void main()
{
int c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=add(a,b); /* Actual Arguments */
printf("The sum of two numbers is %d",c);
getch();
}
int add(int x,int y) /* Formal arguments */
{
int c;
c=x+y;
return(c);
Every ‘C’ variable has a characteristic called its Storage Class.
All variables have datatype and storage classes

✔ Keyword
✔ Where it is Declared
✔ Storage Area
✔ Default Initial value
✔ Lifetime of a
variable
1. Local or Auto or Internal variable
2. External or Global variable
3. Static variable
4. Register Variable
Auto variable are always declared #include<stdio.h>
void function1();
within a function and they are
void function2();
local to the function in which they void main()
are declared. Hence they are also {
int m=1000;
named as local variables
function2();
printf("%d\n",m);
Keyword : auto }
Declaration : Inside the function
void function1()
Storage Area : Stack {
Initial Value : Garbage value int m=10;
(At the time of compilation printf("%d\n",m);
}
compiler assigns any value)
Lifetime : Upto that function only void function2()
{
int m=100;
Example :
function1();
auto int x; (or) int x; printf("%d\n",m);
}
A variable which can be access #include<stdio.h>
with in a function and outside the int k;
main function. These variables are void function1();
also named as Global variables or void function2();
void function3();
External variables
void main()
Keyword : extern {
Declaration : Outside of the main() k=20;
function1();
function
function2();
Storage Area : CPU–memory function3();
Initial Value : zero }
void function1() {
Lifetime : Upto the entire program k=k+10;
Example : printf("%d\n",k); }
void function2()
int x; (or) {
main() main() k=k+1000;
printf("%d\n",k);
{ { extern int x; }
} } void function3()
{
k=k+10;
printf("%d\n",k); }
This variable static is constant and /* To print the value of x */
the value is continued in all the #include<stdio.h>
steps. void stat();
Keyword : static void main()
{
Declaration : Inside the function
int i;
Storage Area : CPU – memory for(i=1;i<=5;i++)
Initial Value : Zero stat(); //calling
}
Lifetime : The value of the variable
void stat() //definition
persists between different function {
calls. static int x=0;
Example : printf("x=%d\n",x);
x=x+1;
static int x; }

0
1
2
3
4
5
/* Example 2 */
#include<stdio.h>
#include<conio.h>
void incre(); /* Function prototype
declaration */
void main()
{
clrscr();
incre();
incre();
incre();
getch(); The character Stored in x is A
} The character Stored in x is B
The character Stored in x is C
void incre()
{
static char x=65;
printf("\n The character stored in x
is %c",x++);
}
These variables are stored in CPU #include<stdio.h>
registers and hence they can be #include<conio.h>
void main()
accessed faster than the one which is
{
stored in memory. register int x;
Keyword : register clrscr();
Declaration : Inside the function printf("\n The value is %d",x);
Storage Area : CPU - Register getch();
Initial Value : Garbage value(At the time }
of compilation compiler assigns any
value)
Lifetime : Upto that function only
Example : register int x;
Note : -899
register double x; register float y;
(Garbage Value)
Registers are usually a 16bit therefore it
cannot hold a float or double data type value
which require 52 & 64 bytes respectively for
storing a value. But the compiler would treat
CSC COMPUTER EDUCATION,
as automatic variables
M.K.B.NAGAR
Functions communicate with each
other by passing arguments.
It can be passed in Two Ways
1.Call By Value
2. Call by Reference
Passing
Parameters

Call by value
Call by reference
✔ The values are passed through temporary
variables. Any manipulation to be done only
on these temporary variables.

✔ The called function does not access the


actual memory location of the original
variable and therefore cannot change its
value.
/* CALL BY VALUE EXAMPLE*/
#include<stdio.h>
void add(int,int);
void main()
{
int x,y; Enter two number = 60
20
printf("Enter two number"); The C Value is 80
scanf("\t\t%d %d",&x,&y);
add(x,y);
}
void add(int a,int b)
{
int c=a+b;
printf("\t\tThe C Value is %d",c);
}CSC COMPUTER EDUCATION,
M.K.B.NAGAR
✔ The function is allowed access the actual
memory location(Address) of the argument
(original variable) and therefore can change
the value of the arguments of the calling
routine have to be changed.
/*CALL BY REFERENCE as well as to swap 2 numbers
using pointers */
#include<stdio.h>
void swap(int *,int *);
void main()
{
int a,b;
printf("\nEnter the numbers to swap");
scanf("%d %d",&a,&b);
printf("The values before swapping :");
printf("\n%d %d",a,b);
swap(&a,&b);
}
Continue….
void swap(int *e,int *f)
{
int *temp;
*temp=*e;
*e=*f;
*f=*temp;
printf("\n The swapped values are %d %d",*e,*f);
}

Enter the numbers to swap = 5 NOTE :


6
The values before swapping : 5 6 & 🡪 Address of
The swapped values are : 6 5
* 🡪 Content of
🖎Functions are easier to write and understand
🖎 The arguments are seperated by commas
🖎 The body of the function may consist of one or many
statements
🖎 It cannot be defined within another function
🖎 Function prototype is a function declaration that specifies
the data types of the arguments
🖎 Calling one function from within another is said to be nesting
of Function calls
🖎 main() returns an integer which is generally the operating
system
Session Summary

🖎 A function is a self contained program segment (block of statements) that performs

some specific well defined task.

🖎Three steps in using a function are defining a function, prviding a prototype and calling

the function.

🖎 Return statement is used to return the information from the function to the calling

portion of the program

🖎 Scope of a variable is defined as the region over which the variable is visible or valid.
EXERCISES

1. Write a program to sort the numbers in ascending order using functions?

2. Write a program to calculate xn using functions?

3. Write a program to check whether the year is leap year or not using functions?

4. Write a program to find the square of first N Numbers and to calculate its sum?

5. Write a program to swap two numbers using functions?


if(len1 == len2)
{
#include<stdio.h> len = len1;
#include<conio.h> for(i=0; i<len; i++)
#include<string.h> {
int main() found = 0;
{ for(j=0; j<len; j++)
char str1[20], str2[20]; {
int len, len1, len2, i, j, found=0, if(str1[i] == str2[j])
not_found=0; {
printf("Enter first string: "); found = 1;
gets(str1); break;
printf("Enter second string: "); }
gets(str2); }
len1 = strlen(str1); if(found == 0)
len2 = strlen(str2); {
not_found = 1;
break;
}
}
if(not_found == 1)
printf("\nStrings are not Anagram");
else
printf("\nStrings are Anagram");
}
else
printf("\nBoth string must contain
same number of character to be an
Anagram Strings");
getch();
return 0;
}
// C Program to Display Armstrong
// numbers between 1 to 1000
#include <stdio.h> else
#include <math.h> {
sum = pow(num % 10, 3) +
int main() pow((num % 100 - num % 10) / 10, 3) +
{
pow((num % 1000 - num % 100) / 100, 3);
int i, digit1, digit2, digit3, sum, num;
printf("All Armstrong number between 1 and if (sum == i)
1000 are:\n"); {
printf("%d ", i);
// This loop will run for 1 to 1000 }
for (i = 1; i <= 1000; i++) }
{ }
num = i; }
// All single digit numbers are Armstrong
number.
if (num <= 9)
{
printf("%d ", num);
}
C – Miscellaneous functions
functions such as getenv(), setenv(), putenv() and other
functions perror(), random() and delay() are given below.

Miscellaneous functions Description


getenv() This function gets the current value of the
environment variable
setenv() This function sets the value for environment
variable
putenv() This function modifies the value for environment
variable
perror() Displays most recent error that happened during
library function call
rand() Returns random integer number range from 0 to
at least 32767
delay() Suspends the execution of the program for
particular time
EXAMPLE PROGRAM FOR GETENV() FUNCTION IN C:
This function gets the current value of the environment
variable.
Let us assume that environment variable DIR is assigned to
“/usr/bin/test/”. Below program will show you how to get this
value using getenv() function.
#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Directory = %s\n", getenv("DIR"));
return 0;
}
OUTPUT:
/usr/bin/test/
EXAMPLE PROGRAM FOR SETENV()
FUNCTION IN C:
This function sets the value for
environment variable.
Let us assume that environment variable
“FILE” is to be assigned
“/usr/bin/example.c”. Below program will
show you how to set this value using
setenv() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("FILE","/usr/bin/example.c",50);
printf("File = %s\n", getenv("FILE"));
return 0;
}
OUTPUT:
File = /usr/bin/example.c
EXAMPLE PROGRAM FOR PUTENV() FUNCTION IN C:
This function modifies the value of environment variable.
Below example program shows that how to modify an existing
environment variable value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("DIR","/usr/bin/example/",50);
printf("Directory name before modifying = " \
"%s\n", getenv("DIR"));

putenv("DIR=/usr/home/");
printf("Directory name after modifying = " \
"%s\n", getenv("DIR"));
return 0;
}
OUTPUT:
Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/
EXAMPLE PROGRAM FOR RAND()
FUNCTION IN C:
This function returns the random integer
numbers range from 0 upto 32767.

#include<stdio.h>
#include<stdlib.h>

#include<time.h>

int main ()

printf ("1st random number : %d\n", rand() %


100);
printf ("2nd random number : %d\n", rand() %
100);
printf ("3rd random number: %d\n", rand());

return 0;

}
OUTPUT:
1st random number : 83
2nd random number : 86
3rd random number: 16816927
EXAMPLE PROGRAM FOR PERROR() FUNCTION IN
C:
This function displays most recent error that happened
during library function call.

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

int main()
{
FILE *fp;
char filename[40] = "test.txt";

/* Let us consider test.txt not available */

fp = f open(filename, "r");

if(fp == NULL)
{
perror("File not found");
printf("errno : %d.\n", errno);
return 1;
}
printf("File is found and opened for reading");
fclose(fp);
return 0;
}
OUTPUT:
errno : 22.
File not found: No such file or directory
EXAMPLE PROGRAM FOR DELAY()
FUNCTION IN C:
This function suspends the execution of the
program for particular time.

C
#include<stdio.h>
#include<stdlib.h>

int main ()

printf("Suspends the execution of the program


"\
"for particular time");

delay(5000); // 5000 mille seconds

return 0;

}
OUTPUT:
Suspends the execution of the program for
particular time

You might also like