Cfunc
Cfunc
Cfunc
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
}
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
Eg: main()
1) Function declaration
void add();
2) Calls to the Function
3) Function definition
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);
}
#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 = The
num1declarator
+ num2; must agree with the
declaration: It must use the same function
printf("%d",sum);
name, have the same argument types in
} the same order (if there are arguments),
and have the same return type.
Summary: Function Components
****************************************
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.
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> numb2)
#include<conio.h> {
void swap(int&, int&); if(numb1>numb2)
int main() {
{ int temp=numb1;
int n1=99, n2=11; numb1=numb2;
int n3=22,n4=88; numb2=temp;
swap(n1,n2); }
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.
#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();
}
}