0% found this document useful (0 votes)
14 views23 pages

Unit 5

unit5 ppsc

Uploaded by

mounica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views23 pages

Unit 5

unit5 ppsc

Uploaded by

mounica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT-5

FUNCTIONS

A function can be defined as a collection or block of code which performs a specific


task.

Ex: the task can be

• Adding two numbers


• Substraction of two numbers,..

Advantages of functions:

• Functions are mainly used for reusing the code or code reusability i.e a code
once written can be used any number of times.
• Functions eliminates redundancy ie there is no duplication of data.
• Functions reduces the length\size of the program.

Types of functions:

• Functions are classified into 2 types


1. Standard library or predefined functions
2. User defined functions

Standard library or predefined functions:

These are already defined in the respective header files.

Library function are

1. Functions in header file stdio.h:

I. getchar()-used to read a single character from keyboard


II. scanf()-used to read different types of data from the
keyboard(int,char,float,double,string)
III. gets()-used to read a string including blankspace.
IV. putchar()-used to print a single character
V. printf()-used to print different types of data
VI. puts()-used to print a string.
2. Functions in header file conio.h:
I. clrscr()-used to clear the output screen.
II. getch()- will make the output screen to wait until a character is
given.
3. Functions in header file string.h:
I. strlen()-to calculate the length of the string
II. strcpy()-used to copy the contents of one string into another
string.
III. strrev()-used to reverse the given string
IV. strcmp()-used to compare two strings
V. strcat()-used to concatenate two strings.
4. Functions in header file math.h:
I. sqrt()-used to calculate square root of a given number.
II. pow()-used to calculate power of a given number.
5. Functions in header file alloc.h:
I. calloc() and malloc()-used to allocate memory to a pointer
variableduring runtime or execution time.
II. realloc()-used to change the size of previously allocated memory
block.
III. free()-used to free the memory allocated by malloc() and calloc()
functions.

User defined functions:

The functions which are defined by the user are known as user defined functions.

Elements/parts/properties of user defined functions:

1. Function declaration/Function prototype


2. Function definition
3. Function call

1.Function declaration/Function prototype:

Syntax:

returntype function name(datatype var1,datatype var2,…);

Return type:

• Return type represents the type of value that will be returned to the calling
function as a result of the processing performed by called function.

Function name:

• Function name is a valid name of the function

• Naming a function follows the same rules as naming variables.

• A function should have a meaningful name that must specify the task that the
function will perform.

Arguments or parameters:
• Datatype var1,datatype var2,… is a list of variables of specified datatypes

• These are known as arguments or parameters

Ex: float sum(int a ,int b);

Ex: void print();

• Function must be declared before the function call.

2.Function definition:

• When a function is defined,space is allocated for that function in the memory.

• A function definition consists of

1. function header

2. function body

Syntax:

returntype functionname(datatype var1,datatype var2,….)

{
------

------

return(variable);

Ex:

float sum(int a,float b)

return(a+b);

3.Function call:

• Function call statements invokes the function.

• When a function is invoked,the compiler jumps to the called function to execute


the statements that are part of that function.
• Once the function is executed,the program control passes back to the calling
function.

Syntax:

• functionname(var1,var2,..);

• Ex: sum(a,b);

Example program for function:

#include<stdio.h>

#include<conio.h>

float sum(int a, float b);//function declaration is done before main()

main()

int a;

float b,add;

printf(“enter two numbers\n”);

scanf(“%d%f”,&a,&b);

add=sum(a,b);

printf(“sum =%f”,add);

float sum(int a,float b)

return(a+b);

Types of functions based on parameters and return type:

• There are 4 types of functions

1. Function without arguments and no return type

2. Functions with arguments and no return type


3. Functions with arguments and having return type

4. Functions without arguments and having return type

1.Function without arguments and no return type:

Synatx:

Void functionname(void) functionname()

{ {

---- or ----

---- ----

} }

Example program:

#include<stdio.h>

main()

add();

add()

int a,b,sum=0;

printf(“enter the values of a and b\n”);

scanf(“%d%d”,&a,&b);

sum=a+b;

printf(“sum is %d\n”,sum);

Note:user defined functions are designed outside main function

2.Functions with arguments and no return type:


Synatx:

functionname(datatype var1,datatye var2,….)

----

----

Example program:

main()
{

int a,b;

printf(“enter two values\n”);

scanf(“%d%d”,&a,&b);

add(a,b);

add(int x, int y)

int z;

z=x+y;

printf(“sum is %d\n”,z);

3.Functions with arguments and having return type:

synatx:

returntype functionname(datatype var1,datatye var2,….)

----

----
return expression;

Example program:

main()
{

int a,b,c;

printf(“enter two values\n”);

scanf(“%d%d”,&a,&b);

c=add(a,b);

printf(“sum is %d\n”,c);

int add(int x, int y)

int z;

z=x+y;

return z;

4.Functions without arguments and having return type:

synatx:

returntype functionname()

----

----

return expression;

}
Example program:

main()

int sum=0;

sum=add();

printf(“sum is %d\n”,sum);

int add()

int a,b,res=0;

printf(“enter two values\n”);

scanf(“%d%d”,&a,&b);

res=a+b;

return res;

PARAMETER PASSING METHODS/PASSING PARAMETERS TO FUNCTIONS:

• In c there are 2 types of parameter passing methods:


1. Call by value or pass by value.
2. Call by reference or pass by reference.

1.Call by value or pass by value:

• When we call any function by passing values as parameters then it is called call
by value.
Ex: add(a,b);
Add(10,20);
• In call by value,if we change the formal arguments that will not change the
actual arguments.

Example program for swapping two values using call by value:

#include<stdio.h>

main()
{

int a=10,b=20;

swap(a,b);

printf("after swapping a=%d\tb=%d\t",a,b);

swap(int a,int b)

int temp;

temp=a;

a=b;

b=temp;

printf("after swapping a=%d\tb=%d\t",a,b);

2.Call by reference or pass by reference:

• When we call any fuction by passing address as parameters then it is called as


call by reference.
Ex: add(&a,&b);
• In call by reference,if we change the formal arguments,it will effect the actual
arguments.

Example program for swapping two values using call by reference:

#include<stdio.h>

main()

int a=10,b=20;

swap(&a,&b);

printf("after swapping a=%d\tb=%d\t",a,b);

}
swap(int *a,int *b)

int temp;

temp=*a;

*a=*b;

*b=temp;

printf("after swapping a=%d\tb=%d\t",*a,*b);

Passing Pointers to Functions:

When we pass a pointer as an argument instead of a variable then the address of the
variable is passed instead of the value. So any change made by the function using the
pointer is permanently made at the address of passed variable. This technique is
known as call by reference in C.

#include<stdio.h>

main()

int a,b;

printf("enter the values of a and b\n");

scanf("%d%d",&a,&b);

add(&a,&b);

add(int *x,int *y)

int c;

c=*x+*y;

printf("sum is %d\n",c);

}
Passing Array to Functions:

Example program for adding individual elements of array by passing array as


parameters to function:

#include<stdio.h>

main()

int a[5]={10,20,30,40,50};

sum(a);

sum(int a[5])

int sum,i;

for(i=0;i<5;i++)

sum=sum+a[i];

printf("sum is %d\n",sum);

Pointer to functions:

#include<stdio.h>

int add(int,int);

main()

int a;

int (*ptr)(int,int);
ptr=&add;

a=(*ptr)(10,20);

printf("a=%d\n",a);

int add(int a,int b)

return a+b;

Recursive functions:

The function called by itself is called recursive function and the process is
called Recursion.

Example program to calculate the factorial of given number using


Recursive function:

#include<stdio.h>

main()

int n,res;

printf("enter any number to perform factorial\n");

scanf("%d",&n);

res=fact(n);

int fact(int n)

int res;

if(n==0)

return 1;
}

else

res=n*fact(n-1);

printf("factorial of number is %d\n",res);

Text Input / Output:

Files:

• A file is a collection of data

Or

A file is a collection of records

• files are stored in secondary storage devices

File Usage:

• When a program is terminated the entire data will be lost.so storing data in files
will preserve the data even if the program is terminated.

• Files can be easily moved from one system to another system.

Streams:

• In C all input and output is done with streams.

• Stream is nothing but the sequence of bytes of data.

• A sequence of bytes flowing into program is called input stream.

• A sequence of bytes flowing out of the program is called output stream.

Standard Library I/O Functions:

• The standard input and output library is stdio.h, and you will find that you
include this library in almost every program you write.
• It allows printing to the screen and collecting input from the user. The
functions you will use the most include:

• printf() is output to the screen

• scanf() is read input from the screen

• getchar() is return characters typed on screen

• putchar() is output a single character to the screen

• fopen() is open a file, and

• fclose() is close a file

Formatting Input /Output Functions:

fprintf() function:

• The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.

• Syntax:

• fprintf(filepointer,”message to be displayed”,variableslist);

#include <stdio.h>

main()

FILE *fp;

fp = fopen("file.txt", "w");//opening file

fprintf(fp, "Hello file by fprintf...\n");//writing data into file

fclose(fp);//closing file

fscanf():

The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.

Character Input / Output Functions:

• Character input functions is used to input a single character.


• All these functions are available in 'stdio.h' header file.

• getchar(): Use to input single character at a time.

Syntax: char variablename = getchar();

• putchar():used to output single character on the screen

Syntax:putchar(variablename);

Example program:

#include<stdio.h>

main()

char a;

printf("enter a character\n");

a=getchar();

printf("the charcter is\n");

putchar(a);

• fputc()-write characters to file

Syntax:fputc(variable or value,filepointer);

Ex:fputc(‘M’,ptr);

Example Program:

#include<stdio.h>

main()

FILE *fp;

fp=fopen("sample.txt","w");

if(fp==NULL)

{
printf("unable to open file\n");

else

printf("file opened successfully\n");

fputc('m',fp);

fputc('o',fp);

fputc('u',fp);

fclose(fp);

fgetc():
fgetc() is used to obtain input from a file single character at a time.

#include<stdio.h>

main()

FILE *fp;

char ch;

fp=fopen("sample.txt","r");

if(fp==NULL)

printf("unable to open file\n");

else

{
printf("file opened successfully\n");

while((ch=fgetc(fp))!=EOF)

printf("%c",ch);

fclose(fp);

Binary Input / Output: Text versus Binary Streams(Types of files or text vs binary
stream):

Files are classified into 2 types

1.Text files

2.Binary files

1.Text files:

• Text files consists of alphabets,digits,special characters.

• Text files are easily understandable by the user.

• Data will be stored in ASCII value

• It provides less security.

• Ex: .c,.txt,.doc,..

2.Binary files:

• Binary files contains data in binary form i.e., 0’s and 1’s.

• Binary files are easily understandable by the computer.

• It provides security when compared to text files.

• Ex: .bin,.exe,…

Functions for Files/file handling functions:


• File handling in C enables us to create, update, read, and delete the files stored
on the local file system through our C program.

• The following operations can be performed on a file.

• Creation of the new file

• Opening an existing file

• Reading from the file

• Writing to the file

• Closing the file

There are many functions in the C library to open, read, write, search and close the
file.

A list of file functions are given below:

Opening File: fopen()

• We must open a file before it can be read, write, or update.


• The fopen() function is used to open a file.

• We can use one of the following modes in the fopen() function.

Syntax:

FILE *ptr;

ptr=fopen(“filename.txt”,”mode”);

• The fopen() function accepts two parameters:


• The file name (string). If the file is stored at some specific location, then we
must mention the path at which the file is stored. For example, a file name
can be like "c://some_folder/some_file.ext".
• The mode in which the file is to be opened. It is a string.

Closing File: fclose()

• The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.

• The syntax of fclose() function is given below:


fclose(filepointer);

fprintf() function:

• The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.

Syntax:

fprintf(filepointer,”message to be displayed”,variableslist);

Example program:

#include <stdio.h>

main(){

FILE *fp;

fp = fopen("file.txt", "w");//opening file

fprintf(fp, "Hello file by fprintf...\n");//writing data into file

fclose(fp);//closing file

The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.

fseek():

The function fseek() is a standard library function in C language, present


in stdio.h header file. It is used to move or change the position of the file pointer
which is being used to read the file, to a specified offset position.

Syntax: fseek(filepointer name,offset,origin);

• The parameter origin can have the following three values

• SEEK_END : denotes the end of the file

• SEE_SET : denotes the starting of the file

• SEEK_CUR : denotes the current position of the file pointer.

Example program:

main()

{
FILE *fp;

char c;

fp=fopen(“sample.txt”,”r”);

if(fp==NULL)

Printf(“cant open file\n”);

fseek(fp,5,SEEK_SET);

c=fgetc(fp);

fseek(fp,-2,SEEK_CUR);

c=fgetc(fp);

fclose(fp);

ftell():

The ftell() function returns the current file position of the specified stream.

Syntax:

long int ftell(FILE *stream)


Example:
#include <stdio.h>
#include <conio.h>
void main (){
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}
rewind():
The rewind() function sets the file pointer at the beginning of the stream.

Syntax:

void rewind(FILE *stream)

Converting File Type:

Converting one file type into another file type

1.converting text file into binary file.

2.converting binary file into text file

Program to convert the text file into Binary file:

#include<stdio.h>

main()

char name[20];

FILE *fptr1;

FILE *fptr2;

fptr1=fopen(“student.txt”,”r”);

fscanf(fptr1,”%s”,name);

printf(“%s”,name);

fptr2=fopen(“Binary.txt”,”w”);

fwrite(&name,sizeof(name),1,fptr2);

fclose(fptr1);

fclose(fptr2);

You might also like