0% found this document useful (0 votes)
2 views21 pages

CP Unit-5 Notes

This document provides an introduction to functions in C programming, detailing their definition, advantages, and components such as declaration, definition, and calling. It explains the differences between standard and user-defined functions, along with examples of function calls and parameter passing methods including call by value and call by reference. Additionally, it covers inter-function communication and the importance of function prototypes in program structure.

Uploaded by

Jyothi Yadla
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)
2 views21 pages

CP Unit-5 Notes

This document provides an introduction to functions in C programming, detailing their definition, advantages, and components such as declaration, definition, and calling. It explains the differences between standard and user-defined functions, along with examples of function calls and parameter passing methods including call by value and call by reference. Additionally, it covers inter-function communication and the importance of function prototypes in program structure.

Uploaded by

Jyothi Yadla
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/ 21

UNIT-5

Introduction to Functions:

Definition: A Function is a group of statements that can perform any particular task.

Advantages of Functions
There are several advantages in using functions. They are discussed below.
1. When developing even a program, it is very difficult, to write the entire program as a single large main function.
The task to be performed is normally divided into several independent subtasks, thereby reducing the overall
complexity.
2. Writing a program in single large function i.e in main(),Such programs are very difficult to test, debug and
maintain. The task to be performed is normally divided into several independent subtasks, thereby it is easy to read,
test, debug and maintain.
3. Functions help avoid duplication of effort and code in programs. During the development of a program, the same
or similar activity may be required to be performed more than once. The use of functions in such situations avoids
duplication of effort and code in programs i.e code can be reused.
4. This reduces the size of the source program as well as the executable program, thus reducing program
development and maintenance cost.
5. Functions enable us to hide the implementation details of a program, e. g., we have used library functions such as
sqrt, log, sin, etc. without ever knowing how they are implemented.
6. The functions developed for one program can be used, if required, in another program with little or no
modification. This further reduces program development time and cost
Every function in C has the following...

 Function Declaration (Function Prototype)


 Function Definition
 Function Call

Function Declaration (Function Prototype):


The function declaration tells the compiler about function name, the data type of the return value and
parameters. The function declaration is also called a function prototype. Before using the function in the program first
it must be declared globally i.e before main( ).
Syntax:
returnType functionName( parametersList ) ;

 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function.
 Parameters – is the information passed to a function. In function declaration only data types of variables
passed to a function must be used.
Example:
int addition (int , int) ;
here the function returns an integer value so return tyoe of the function is int.

Function Definition:
It contains the actual statements which are to be executed. The function definition is also known as the body
of the function. The actual task of the function is implemented in the function definition.
The function definition can be placed after main( ) function and its function declaration must be done before
main( ).
If function definition is placed before main( ) then no need to declare the function .
Syntax:
returnType functionName( parametersList )
{
Body of function;
}

 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function.
 Parameters – is the information passed to a function. In function definition variables passed must be
declared with its datatypes..

 Function Body − The function body set of statements placed inside ‟ { }‟


Example:
Function declaration is
int addition(int , int) ;

Function definition is
int addition (int a , int b)
{
return (a+b);
}
The no: of parameters or arguments and function name, return type in function declaration and function
definition must match otherwise compiler will generate error.
Function Call:
To execute the function definition a function must be called. When a function call is executed, the execution
control jumps to the function definition where the actual code gets executed.
Syntax: function without returning value

functionName( parameters );
here parameters are variables separated by comma
Syntax: function with returning value

Variable = functionName( parameters );


Example:
c = addition( a , b);
Here variable C stores the value retured by function addition( )
Working of function:

1. Firstly Operating System will call our main


function.
2. When control comes inside main function,
execution of main starts (i.e execution of C
program starts).
3. A control come to 1st statement and executes it
and then it goes to 2nd statement in this way in an
order execution takes place.
4. Assume the 3rd statement inside main( ) is
functionname( ) .when function is called then
control jumps to its function definition and the
statements inside functionname( ) will gets
executed.
5. After executing the function control returns to
main( ) and executes the statement after the
function call i.e 4th statement.
6. Main ( ) function ends.
7. C program terminates

Return statement: It is used to return a value from a function

Syntax: return value;

Or return (expression)

C program to perform addition operation on two integers using functions:


#include<stdio.h>
int addition ( int , int); // function declaration
void main()
{
int a, b, c;
printf(“Enter any two numbers\n ”);
scanf(“%d%d”, &a, &b);
c = addition(a, b); // function call
printf(“the result is %d\n”, c);
}
int addition(int x, int y) // function definition
{
return (x + y);
}
Output:
Enter any two numbers
2 3
the result is 5

Types of functions:
1. Standard functions or predefined functions and
2. Userdefined functions
Standard Functions in C
The standard functions are built-in functions. In C programming language, the standard functions are declared
in header files and defined in .dll files. In simple words, the standard functions can be defined as "the readymade
functions defined by the system to make coding more easy". The standard functions are also called as library
functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file using #include statement.
For example, the function printf() is defined in header file stdio.h (Standard Input Output header file). When we
use printf() in our program, we must include stdio.h header file using #include<stdio.h> statement.
C Programming Language provides the following header files with standard functions.
Header File Purpose Example Functions

stdio.h Provides functions to perform standard I/O operations printf(), scanf()

conio.h Provides functions to perform console I/O operations clrscr(), getch()

math.h Provides functions to perform mathematical operations sqrt(), pow()

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general functions/td> calloc(), malloc()

time.h Provides functions to perform operations on time and date time(), localtime()

ctype.h Provides functions to perform - testing and mapping of character data values isalpha(), islower()

setjmp.h Provides functions that are used in function calls setjump(), longjump()

signal.h Provides functions to handle signals during program execution signal(), raise()

assert.h Provides Macro that is used to verify assumptions made by the program assert()

locale.h Defines the location specific settings such as date formats and currency setlocale()
symbols

stdarg.h Used to get the arguments in a function if the arguments are not specified by va_start(), va_end(),
the function va_arg()

errno.h Provides macros to handle the system calls Error, errno

graphics.h Provides functions to draw graphics. circle(), rectangle()

User defined functions:

The functions that are created by the user in a program are known as user defined functions.

Every User defined function in C has the following...


 Function Declaration (Function Prototype)
 Function Definition
 Function Call
Function Declaration (Function Prototype):
The function declaration tells the compiler about function name, the data type of the return value and
parameters. The function declaration is also called a function prototype. Before using the function in the program first
it must be declared globally i.e before main( ).

Syntax:
returnType functionName( parametersList ) ;

 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function.
 Parameters – is the information passed to a function. In function declaration only data types of variables
passed to a function must be used.
Example:
int addition (int , int) ;
here the function returns an integer value so return tyoe of the function is int.

Function Definition:
It contains the actual statements which are to be executed. The function definition is also known as the body
of the function. The actual task of the function is implemented in the function definition.
The function definition can be placed after main( ) function and its function declaration must be done before
main( ).
If function definition is placed before main( ) then no need to declare the function .
Syntax:
returnType functionName( parametersList )
{
Body of function;
}
 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function.
 Parameters – is the information passed to a function. In function definition variables passed must be
declared with its datatypes..
 Function Body − The function body set of statements placed inside ‟ { }‟
Example:
Function declaration is
int addition(int , int) ;

Function definition is
int addition (int a , int b)
{
return (a+b);
}
The no: of parameters or arguments and function name, return type in function declaration and function
definition must match otherwise compiler will generate error.

Function Call:
To execute the function definition a function must be called. When a function call is executed, the execution
control jumps to the function definition where the actual code gets executed.
Syntax: function without returning value

functionName( parameters );
here parameters are variables separated by comma
Syntax: function with returning value

Variable = functionName( parameters );


Example:
c = addition( a , b);
Here variable C stores the value retured by function addition( )
Different ways to make a User defined function call
1. From main function
2. From another user-defined function
3. From same function (recursive)

1. From main function 2.From another user-defined function

3.From same function (recursive)

C program to perform addition operation on two integers using User defined functions:
#include<stdio.h>
int addition ( int , int); // function declaration
void main()
{
int a, b, c;
printf(“Enter any two numbers\n ”);
scanf(“%d%d”, &a, &b);
c = addition(a, b); // function call
printf(“the result is %d\n”, c);
}
int addition(int x, int y) // function definition
{
return (x + y);
}
Output:
Enter any two numbers
2 3
the result is 5
Important terms in functions
1. Calling Function: It is used to initiate the function execution. The function call present inside main() or in
any other function is called calling function.
2. Called Function: It is nothing but the function definition. It decides what is to be done by the function on
a function call.
3. Actual parameters: Parameters inside the calling function are called actual parameters.
4. Formal parameters: Parameters inside the called function are called formal parameters.
For example, consider the following program...
#include<stdio.h>
int addition(int, int) ;
void main()
{
int a=10, b=20, result ;
result = addition(a, b) ; calling function

printf("Sum = %d", result); Actual parameters are a and b


}
int addition(int x, int y) called function
{
return (a+b) ;
} Formal parameters are x and y

Inter Function Communication in C


When a function gets executed in the program, the execution control is transferred from calling a function to
called function and executes function definition, and finally comes back to the calling function. In this process, both
calling and called functions have to communicate with each other to exchange information. The process of
exchanging information between calling and called functions is called inter-function communication.
In C, the inter function communication is classified as follows...
 Downward Communication
 Upward Communication
 Bi-directional Communication
1) Downward Communication:
In this type of inter function communication, the data is transferred from calling function to called function
but not from called function to calling function. The functions with parameters and without return value are
considered under downward communication.
For example, consider the following program...
#include<stdio.h>
void addition(int, int) ;
void main()
{
int a=10, a=30 ;
addition(a, b) ; // calling function
}
void addition(int a, int b) // called function
{
int c;
c=a+b;
printf("Sum = %d", c) ;
}
Output:
Sum=30

2) Upward Communication:
In this type of inter-function communication, the data is transferred from called function to calling-function
but not from calling-function to called-function. The functions without parameters and with return value are
considered under upward communication.
For example, consider the following program...
#include<stdio.h>
int addition() ;
void main()
{
int result ;
result = addition() ; // calling function
printf("Sum = %d", result) ;
}
int addition() // called function
{
int a=10, a=30 ;
return (a+b) ;
}
Output:
Sum=30

3)Bi - Directional Communication:


In this type of inter-function communication, the data is transferred from calling-function to called function
and also from called function to calling-function. The functions with parameters and with return value are considered
under bi-directional communication.
For example, consider the following program...
#include<stdio.h>
int addition(int, int) ;
void main()
{
int a=10, b=20, result ;
result = addition(a, b) ; // calling function
printf("Sum = %d", result) ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}
Output:
Sum=30

Parameters passing methods to function:

• Parameters can be passed to a function in two ways. They are:


• Call by value
• Call be reference
1. Call by value:

In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called function. The changes made on the formal parameters
does not effect the values of actual parameters. That means, after the execution control comes back to the calling
function, the actual parameter values remains same.
c program to swap two integer variables using function (call by value method)

#include<stdio.h>
void swap( int, int);
void main( )
{
int a , b;
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
printf(“before swapping a= %d \t b=%d\n” , a, b);
swap( a, b);
printf(“after swapping a= %d \t b=%d\n” , a, b);
}
void swap( int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter a and b values
10 20
before swapping a= 10 b=20
After swapping a= 10 b=20

2. Call be reference (passing pointers to functions):


In Call by Reference parameter passing method, the memory location address of the actual parameters is
copied to formal parameters. This address is used to access the memory locations of the actual parameters in called
function. In this method of parameter passing, the formal parameters must be pointer variables
Whenever we use these formal parameters in called function, they directly access the memory locations of
actual parameters. So the changes made on the formal parameters effects the values of actual parameters.

c program to swap two integer variables using function (call by reference)


#include<stdio.h>
void swap( int*, int*);
void main( )
{
int a , b;
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
printf(“before swapping a= %d \t b=%d\n” , a, b);
swap(&a , &b);
printf(“after swapping a= %d \t b=%d\n” , a, b);
}
void swap( int *a, int *b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter a and b values
10 20
before swapping a= 10 b=20
After swapping a= 20 b=10

Passing arrays to functions:

To pass a single-dimension array as an argument in a function call , simply use arrayname.


Syntax:
function_name(arrayname);
Example:
int a[10];
Function call:
sum( a ) ;

To pass a single-dimension array as an argument in a function definition. There are three ways :

Way- 1: formal parameter as pointer


void sum (int *p)
{
statements;
}
Here pointer p stores base address of array „ a „.
Function declaration: void sum (int *);

Way- 2: formal parameter sized array


void sum (int p[10])
{
statements;
}
Here pointer p is array contains values of array „a‟.
Function declaration : void sum (int[ ]);

Way- 3: formal parameter unsized array


void sum (int p[ ])
{
statements;
}
Here pointer p is array contains values of array „a‟.
Function declaration : void sum (int [ ]);

c program to funs sum of all elements of array using functions:


#include<stdio.h>
void sum(int [ ] ,int);
void main( )
{
int a[10] ,n , i;
printf(“enter the size of array\n”);
scanf(“%d”,&n);
printf(“enter the elements\n”);
for( i =0 ; i<n ; i++)
scanf(“%d”, &a[ i ] );
sum( a , n);
}
void sum( int p[ ] , int size)
{
int sum=0 ,i ;
for(i=0 ;i<size; i++)
sum = sum + p[ i ];
printf(the sum of elements is %d\n”, sum);
}
Output:
enter the size of array
5
enter the elements
1 2 3 4 5
the sum of elements is 15

Character Input / Output Functions

Character Input functions:


1) getch() :Used to input single character at a time. But it will not display input character while the user is
inputting a character . get stands for input, ch stands for character. getch() is a nonstandard function and is
present in <conio.h> header file which is mostly used by MS-DOS compilers like Turbo C. This function will not
require enter key to terminate.
Syntax: char a = getch();
Here variable „a‟ contains character entered by user.
Program to read and display single character using getch()
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getch();
printf("The character is : %c\n",a);
}
Output:
Enter character
The character is : L

In the above program user pressed chatacter L (no need to press enter key to terminate) , getch() function will
not show L during inputting.

2) getche(): It is same as getch() function but it will display input character. get stands for input, ch
stands for character, e stands for echo(display). This function will not require enter key to terminate.
Syntax: char a = getch();
Here variable a contains character entered by user.
Program to read and display single character using getche()
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getche();
printf("The character is : %c\n",a);
}
Output:
Enter character
L
The character is : L

In the above program user pressed chatacter L (no need to press enter key to terminate) , getche() function
will not show L during inputting but it shows input character L after user screen is displayed.

3)getchar():Used to input single character .It will terminate by enter key after inputting a single
character. getchar() is a standard function and is present in <stdio.h>
Syntax: char a = getchar();
Here variable a contains character entered by user.
Program to read and display single character using getchar()
#include<stdio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getchar();
printf("The character is : %c\n",a);
}
Output:
Enter character
L
The character is : L

Character Output functions:


1) putch(): used to print a single alphanumeric character. It is a nonstandard function and is present in <conio.h>
header file which is mostly used by MS-DOS compilers like Turbo C.
Syntax: putch(a);
Here variable a contains character entered by user
Program to read and display single character
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getchar();
printf("The character is");
putch(a);
}
Output 1:
Enter character
2
The character is : 2
Output 2:
Enter character
L
The character is : L
2) putchar(): used to print a single character. It is a standard function and is present in <stdio.h> header file.
Syntax: putchar(a);
Here variable a contains character entered by user
Program to read and display single character using getchar()
#include<stdio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getchar();
printf("The character is");
putchar(a);
}
Output:
Enter character
L
The character is : L

File:

Generally, a file is used to store user data in a computer. In other words, computer stores the data using files.
we can define a file as follows.
File is a collection of data that stored on secondary memory like harddisk of a computer.

C programming language supports two types of files and they are as follows...

 Text Files (or) ASCII Files


 Binary Files
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and symbols is called text
file (or) ASCII file.
Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary file. Generally, the binary
files are compiled version of text files.

File Handling Functions in C


The following are the operations performed on files in the c programming language...
 Creating (or) Opening a file
 Closing a file
 Reading data from a file
 Writing data into a file
1) Creating (or) Opening a file using fopen(): To create a new file or open an existing file, a file pointer of FILE
type needs to be declared.
Syntax for declaring file pointer
FILE * fp;
Here fp is a file pointer which contains information, such as size, current file pointer position, type of
file etc., to perform operation on the file.

Opening a file using fopen() function:


The fopen() function takes two arguments the name of the file and the mode in which the file is to be opened.
Mode specifies the purpose of opening the file i.e, whether for reading or writing.
Syntax:
Filepointer = fopen(“filename”,mode);
When fopen() function opens a file in memory, it returns a pointer to this particular file. If fopen() function
can't open the file then it will return NULL.
In C programming language, there different modes are available to open a file and they are shown in the
following table.
S. No. Mode Description

1 r Opens a text file in reading mode.

2 w Opens a text file in wirting mode.

3 a Opens a text file in append mode.

4 r+ Opens a text file in both reading and writing mode.

5 w+ Opens a text file in both reading and writing mode. It


set the cursor position to the begining of the file if it
exists.

6 a+ Opens a text file in both reading and writing mode.


The reading operation is performed from begining and
writing operation is performed at the end of the file.

Example:
FILE * fp;
fp = fopen("file1.txt","r");
The above example code creates a new file called file1.txt if it does not exists otherwise it is opened
in reading mode.

2) Closing a File using fclose() function:

When the reading or writing of a file is finished, the file should be closed properly using fclose() function.
The fclose() function does the following tasks:
 Flushes any unwritten data from memory.
 Discards any unread buffered input.
 Frees any automatically allocated buffer
 Finally, close the file
Syntax:
fclose( *fp )
Here this function closes the file which is pointed by file pointer fp

3) Reading from a file:The reading from a file operation is performed using the following pre-defined file handling
methods.

a.getc():This function is used to read a character from specified file which is opened in reading mode. It reads from
the current position of the cursor. After reading the character the cursor will be at next character
Syntax:
getc( *filepointer )
Example:
FILE *fp;
fp = fopen("MySample.txt","r");
Char ch;
ch=getc(fp);
Here the variable ch contains the first character of the file "MySample.txt" which is pointed by file
pointer fp. To read entire contents in the file then while loop is used.
C program to demonstrate getc() function:
#include<stdio.h> MySample.txt
void main()
{ Welcome
FILE *fp;
char ch;
fp = fopen("MySample.txt","r");
if(fp==NULL)
printf("error to open file\n");
while((ch=getc(fp))!=EOF)
{
printf("%c", ch);
}
fclose(fp);
}
Output:
Welcome

b.getw():This function is used to read an integer value form the specified file which is opened in reading mode. If the
data in file is set of characters then it reads ASCII values of those characters.
Syntax:
getw( *filepointer )
Example:
FILE *fp;
fp = fopen("MySample.txt","r");
Char ch;
ch=getw(fp);
Here the variable ch contains the first character of the file "MySample.txt" which is pointed by file
pointer fp. To read entire contents in the file then while loop is used.

c.fscanf():This function is used to read multiple datatype values from specified file which is opened in reading mode.
Syntax:
fscanf(fp, typeSpecifier, &variableName )
Here fp is a file pointer

Example:
FILE *fp; file.txt
fp = fopen("file.txt","r")
fscanf(fp,”%s%s%d”,s1,s2,&y); Welcome to 2020
here s1 and s2 are character variables and
y is integer variable
the above function reads the contents of
file pointed by file pointer fp and stores them in specified variable i.e s1 contains welcome ,s2 contains
to and y contains 2020
C program to demonstrate fscanf() function:

#include<stdio.h>
void main()
{
char s1[10], s2[10]; file.txt
int y;
Welcome to 2020
FILE * fp;
fp = fopen ("file.txt", "r");
if(fp==NULL)
printf("error to open file\n");
fscanf (fp, "%s %s %d", s1, s2, &y);
printf("Read String1 - %s\n", s1 );
printf("Read String2 - %s\n", s2 );
printf("Read Integer - %d", y );
fclose(fp);
}
Output:
Read String1 - Welcome
Read String2 - to
Read Integer - 2020

d.fgets(): This method is used for reading a set of characters from a file which is opened in reading mode starting
from the current cursor position. The fgets() function reading terminates with reading NULL character.
Syntax:
fgets( str, n, fp)
Here str is a character array variable, fp is a file pointer , n is no:of characters to be read
Example:
FILE *fp; file.txt
fp = fopen("file.txt","r"); Welcome to 2020
fgets( str, 8, fp);
here str is a character variable which contains 1st 7 characters(i.e n-1 characters) of file,txt
o/p: welcome

C program to demonstrate fgets() function:

#include<stdio.h> file.txt
void main()
Welcome to 2020
{
FILE *fp;
char str[20];
fp = fopen ("file.txt", "r");
if(fp==NULL)
printf("error to open file\n");
fgets(str,16,fp);
printf("%s", str);
fclose(fp);
}
Output:
Welcome to 2020

e.fread():This function is used to read specific number of sequence of characters from the specified file which is
opened in reading mode.
Syntax:
fread( str, sizeof(char), n, fp)
Here str is a character array variable, fp is a file pointer , n is no:of characters to be read

Example:
FILE *fp; file.txt
fp = fopen("file.txt","r");
fread( str, 7, fp); Welcome to 2020
here str is a character variable which contains 1st 7 characters of file,txt
o/p: welcome

C program to demonstrate fread() function:


#include<stdio.h>
void main()
{
FILE *fp;
char str[20];
fp=fopen("myfile.txt","r");
if(fp==NULL)
printf("error to open file\n");
fread(str,sizeof(char),15,fp);
printf("%s",str);
fclose(fp);
}
Output:
Welcome to 2020

4. Writing data into a file: The writing into a file operation is performed using the following pre-defined file
handling methods.
a) putc():This function is used to write/insert a character to the specified file when the file is opened in writing mode.
Syntax:
putc(character,fp)
Here character is letter which is to be inserted into file and fp is the filepointer
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
putc(„A‟, fp ); A

C program to demonstrate putc() function:

#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“file.txt","w");
if(fp==NULL)
printf("error to open file\n");
putc(„A‟, fp );
fclose(fp);
}

output: file.txt

b)putw() - This function is used to writes/inserts an integer value to the specified file when the file is opened in
writing mode.
Syntax:
putw(integervalue,fp)
Here integervalue is a digit which is to be inserted into file and fp is the filepointer

Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
putw(20, fp ); 20

C program to demonstrate putw() function:

#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“file.txt","w");
if(fp==NULL)
printf("error to open file\n");
putw(20, fp );
fclose(fp);
}
output: file.txt

20

c)fprintf() - This function is used to writes/inserts multiple lines of text with mixed data types (char, int, float, double)
into specified file which is opened in writing mode.
Syntax:
fprintf (fp ,”text”)
Here fp is the filepointer and text is a string which is to be inserted into file

Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fprintf (fp ,” Welcome to 2020”); Welcome to 2020

C program to demonstrate fprintf () function:


#include<stdio.h>
void main()
{
FILE *fp;
char str[20]=”welcome to 2020”;
fp=fopen("myfile.txt","w");
if(fp==NULL)
printf("error to open file\n");
fprintf (fp,str);
fclose(fp);
}
output: file.txt

Welcome to 2020

d) fputs( ) - This method is used to insert string data into specified file which is opened in writing mode.
Syntax:
fputs( "string", fp )
Here fp is the filepointer and string which is to be inserted into file

Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fputs(fp ,” Welcome to 2020”); Welcome to 2020

C program to demonstrate fputs () function:


#include<stdio.h>
void main()
{
FILE *fp;
char str[20]=”welcome to 2020”;
fp=fopen("myfile.txt","w");
if(fp==NULL)
printf("error to open file\n");
fputs(str,fp);
fclose(fp);
}
output: file.txt

Welcome to 2020

e)fwrite() - This function is used to insert specified number of characters into a binary file which is opened in writing
mode.
Syntax:
fwrite( “StringData”, sizeof(char), N , fp)
Here fp is the filepointer
StringData is string which is to be inserted into file
N is no:of characters to be nserted
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fwrite( “Welcome to 2020”, sizeof(char), 15 , fp) Welcome to 2020

C program to demonstrate fwrite () function:


#include<stdio.h>
void main()
{
FILE *fp;
char str[20]=”welcome to 2020”;
fp=fopen("myfile.txt","w");
if(fp==NULL)
printf("error to open file\n");
fwrite(str, sizeof(char), 15 , fp)
fclose(fp);
}
output: file.txt

Welcome to 2020

Text versus Binary Streams: Difference between text file and binary file
 Text file is human readable because everything is stored in terms of text. In binary file everything is written in
terms of 0 and 1, therefore binary file is not human readable.
 A newline(\n) character is converted into the carriage return-linefeed combination before being written to the
disk. In binary file, these conversions will not take place.
 In text file, a special character(newline), whose ASCII value is 26, is inserted after the last character in the file
to mark the end of file. There is no such special character present in the binary mode files to mark the end of
file.
 In text file, the text and characters are stored one character per byte. For example, the integer value 1245 will
occupy 2 bytes in memory but it will occupy 5 bytes in text file. In binary file, the integer value 1245 will
occupy 2 bytes in memory as well as in file.
Recursion

Definition: A function calling itself is called recursion.

To stop the recursion a base condition must be used

Examples:

To find Factorial of given number n :

Factorial( n ) = 1 if n equals to 0

= n * factorial(n-1) other wise

To find GCD of two numbers n1 and n2:

gcd( n1, n2) = n1 if n2 equals to 0

= gcd( n2 , n1 % n2) otherwise

C program to find factorial of given number using recursion:

#include<stdio.h>
int factorial( int );
int main( )
{
int fact, n;
printf(“Enter any positive integer\n ”);
scanf(“%d”, &n);
fact = factorial( n );
printf(“Factorial of is %d”, fact);
return 0;
}
int factorial( int n )
{
int f;
if( n = = 0)
return 1;
else
f = n * factorial( n-1 );
return f;
}
Output:
Enter any positive integer
3
Factorial of is 6

C program to find GCD of two numbers using recursion

#include <stdio.h>
int gcd(int , int);
int main()
{
int n1, n2,result;
printf("Enter two positive integers\n");
scanf("%d%d", &n1, &n2);
result = gcd(n1 , n2);
printf("G.C.D is %d\n", result);
return 0;
}
int gcd(int n1 , int n2)
{
if (n2 == 0)
return n1;
else
return gcd( n2, n1 % n2);
}
Output:
Enter two positive integers
36 24
G.C.D is 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy