0% found this document useful (0 votes)
6 views

Functions

Uploaded by

fakemail2976
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Functions

Uploaded by

fakemail2976
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Introduction

• C functions can be classified into two categories, namely library functions and
user-defined functions.

• printf() and scanf() belong to the category of library functions and their
definition is written in <stdio.h> header file. Similarly, sqrt(),cos(), strcat(),,
etc are also library functions. It is difficult to implement a large program even
if its algorithm is available. To implement such a program with ease, it should
be split into a number of independent tasks, which can be easily designed,
implemented and managed. C functions can be classified into two categories,
namely library functions and user-defined functions.

• printf() and scanf() belong to the category of library functions and their
definition is written in <stdio.h> header file. Similarly, sqrt(),cos(), strcat(),,
etc are also library functions.
Introduction

• It is difficult to implement a large program even if its algorithm is available.

• To implement such a program with ease, it should be split into a number


of independent tasks, which can be easily designed, implemented and
managed.

• This process of splitting a large program into small manageable tasks and
designing them independently is popularly called modular programming.
Introduction…..

This approach results in a number of advantages:

• The high-level logic of the overall problem is solved first while the details of
each lower-level function are addressed later.

• The length of a source program can be reduced by using functions at


appropriate places. This factor is particularly critical with microcomputers
where memory space is limited.

• It is easy to locate and isolate a faulty function for further investigations.

• A function may be used by many other programs. This means that a C


programmer can build on what others have already done, instead of starting
all over again from scratch.
Introduction…..

• User-defined Functions
• Def:
• A function is a self-contained block of program statements that perform a
particular task.
Introduction…..

Why are functions needed?

The use of functions provides several benefits. It makes programs significantly


easier to understand and maintain by breaking them up into easily manageable
chunks.

Advantages: ​

• Code reuse: The main() function can consist of a series of function calls rather than
countless lines of code.​

• Flexible debugging: Functions make the code shorter and more readable i.e. making it
less likely to have mistakes.​

• Code sharing: A well written function may be reused in multiple programs.​


Introduction…..

• Data protection: Functions can be used to protect data. This is related with
the concept of local data. The local data is available only within a function
when the function is being executed.​

Elements of User-defined Functions

• In order to make use of o user-defined function we need to establish three


elements that are related to functions - Function Definition, Function Call, and
Function Declaration

• The function definition is an independent program module that is specially


written to implement the requirements of the function.

• In order to use the function we need to invoke it at a required place in the


program. This is known as the function call.
Functions
User Defined Function
Introduction…..

The program (or a function) that calls the function is referred to as the calling
program or calling function. The calling program should declare any function that
is to be used later in the program. This is known as the function declaration or
function prototype.

WAP to find the greatest among two numbers using a user-defined


function

#include<stdio.h>
#include<conio.h>
int max(int x, int y); //Function declaration
void main()
{
int a,b,c;
printf("Enter two numbers: ");
Introduction…..

scanf("%d%d",&a,&b);
c=max(a,b); //Function call
printf("\nGreatest Number=%d",c);
getch();
}

int max(int x,int y) //Function definition


{
if(x>y)
return x;
else
return y;
}
Introduction…..

OUTPUT
Enter two numbers: 23
76
Greatest Number=76

Function Definition
A general format of a function definition is given below:
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
…..
return statement;
}
Introduction…..

Where

function_type specifies the type of value (like int or float ) that the function is
expected to return to the program calling the function.

function_name is any valid C identifier and therefore must follow the same rules
of formation as other variable names in C.

parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task.
executable statements perform the task of the function.

Return statement returns the value evaluated by the function.


Introduction…..

Function Call
A function can be called by simply using the function name followed by a list of
actual parameters, if any, enclosed in parentheses.
main()
e.g.
{
int y;
y=mul(10,5); //call
…..
}
int mul(int x, int y)
{
int p;
p=x*y;
return p;
}
Introduction…..

In the above given example, the function computes the product x and y, assigns
the result to the local variable p, and then returns the value 50 to the main()
where it is assigned to y again.

Function Declaration

Like variables, all functions in a C program must be declared, before they are
invoked. The general format is as given below:

function_type function_name (parameter list);


Introduction…..

NOTE: Parameters (also known as, arguments) are used in three places:

• In declaration (prototype),
• In function call, and
• In function definition

The parameters used in declaration (prototypes) and function definitions are


called formal parameters and those used in function calls are called actual
parameters.

The formal and actual parameters must match exactly in type, order and number.
Their names however, do not need to match.
MCQ - 1

1. What is function?

A. Function is a block of statements that perform some specific task.

B. Function is the fundamental modular unit. A function is usually designed


to perform a specific task.

C. Function is a block of code that performs a specific task. It has a name


and it is reusable.

D. All of the above

Answer: D.
Types of Functions

 Function with arguments and return type

 Functions with arguments but no return type

 Functions without arguments but return type

 Functions without arguments and no return type

Function with arguments and return type

 In this type of functions, the called function receives the data from the calling
function.

 After the processing, the called function returns the value to the calling
function.
Types of Functions…..

Example:
/* With arguments and return type */
#include<stdio.h>
#include<conio.h>
int addsum(int x,int y); //Declaration
void main()
{
int a, b, result;
clrscr();
printf("\nEnter the value of a and b:\n");
scanf("%d%d",&a,&b);
result=addsum(a,b); //Call
printf("\nSum=%d”,result);
getch();
}
Types of Functions…..

int addsum(int a,int b) //Definition


{
int sum=0;
sum=x+y;
return sum;
}

Functions with arguments but no return type

 In this type of functions, the called function receives the data from the calling
function for computation.

 After the computation, the called function does not return any value back to
the calling function; it prints that data in its scope only.
Types of Functions…..

Example:
/* With arguments and no return type */
#include<stdio.h>
#include<conio.h>
void addsum(int x,int y); //Declaration
void main()
{
int a, b, result;
clrscr();
printf("\nEnter the value of a and b:\n");
scanf("%d%d",&a,&b);
addsum(a,b); //Call
getch();
}
Types of Functions…..

void addsum(int a,int b) //Definition


{
int sum=0;
sum=x+y;
printf(“\nSum=%d”, sum);
}

Functions without arguments but return type

 In this type of function, the called function does not receive any data from the
calling function for processing.

 After the processing, the called function returns the computed value to the
calling function.
Types of Functions…..

Example:
/* Without arguments but return type */
#include<stdio.h>
#include<conio.h>
int addsum(); //Declaration
void main()

{
int result;
clrscr();
result=addsum(); //Call
printf("\nSum=%d”,result);
getch();
}
Types of Functions…..

int addsum() //Definition


{
int x,y,sum=0;
printf(“\nEnter the value of x and y:\n”);
scanf("%d%d",&x,&y);
sum=x+y;
return sum;
}

Functions without arguments and no return type

 In this type of function, the called function does not receive any data from the
calling function for processing.

 After processing, the called function does not return any data to the calling
function.
Types of Functions…..

Hence, there is no data transfer between the calling function and the called
function.

Example:
/* With no arguments and no return type */
#include<stdio.h>
#include<conio.h>
void addsum(); //Declaration
void main()
{
clrscr();
addsum(a,b); //Call
getch();
}
Types of Functions…..

void addsum() //Definition


{
int x,y,sum=0;
printf(“\nEnter the value of x and y:\n”);
scanf("%d%d",&x,&y);
sum=x+y;
printf("\nSum=%d”,sum);
}
Functions
#include<stdio.h>

int main() {
int num1, num2, res;

printf("\nEnter the two numbers : ");


scanf("%d %d", &num1, &num2);

//Call Function Sum With Two Parameters


res = sum(num1, num2);

printf(“\nAddition of two number is : %d“, res);


return (0);
}

int sum(int num1, int num2) {


int num3;
num3 = num1 + num2;
return (num3);
}
Passing Array to the Function
Character Array
Strings in C

#include<stdio.h> #include<stdio.h>
#include <string.h> void main ()
int main(){ {
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o char s[30];
', 'i', 'n', 't', '\0'}; printf("Enter the string?
char ch2[11]="javatpoint"; ");
gets(s);
printf("Char Array Value is: %s\ printf("You entered
n", ch); %s",s);
printf("String Literal Value is: %s\ }
n", ch2);
return 0;
}
// C Program to print Array of strings

#include <stdio.h>

// Driver code
int main()
{
char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
printf("String array Elements are:\n");

for (int i = 0; i < 3; i++)


{
printf("%s\n", arr[i]);
}
return 0;
}
Here, arr[0] = “GFG”; // This will give an Error which says assignment
to expression with an array type.
double getAverage(int arr[], int size) {

int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = sum / size;

return avg;
}
#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf( "Average value is: %f ", avg );

return 0;
}
// function declaration
void displayDetail(struct student std);

int main(void) {
// creating a student structure template
// creating a student structure array variable
struct student stdArr[3]; struct student {
char firstname[64];
int i;
char lastname[64];
// taking user input char id[64];
for (i = 0; i < 3; i++) {
printf("Enter detail of student #%d\n", (i+1)); int score;
};
printf("Enter First Name: ");
scanf("%s", stdArr[i].firstname);

printf("Enter Last Name: ");


scanf("%s", stdArr[i].lastname);

printf("Enter ID: ");


scanf("%s", stdArr[i].id);

printf("Enter Score: "); void displayDetail(struct student std) {


scanf("%d", &stdArr[i].score); printf("Firstname: %s\n", std.firstname);
}
printf("Lastname: %s\n", std.lastname);
// output printf("ID: %s\n", std.id);
for (i = 0; i < 3; i++) {
printf("\nStudent #%d Detail:\n", (i+1)); printf("Score: %d\n", std.score);
displayDetail(stdArr[i]); }
}

return 0;
}

You might also like