IP-Unit-5-2023-24
IP-Unit-5-2023-24
FUNCTIONS:
Types of Functions :
The functions are classified into standard functions and user-defined
functions.
Standard Functions :
In simple words, the standard functions can be defined as "the ready made
functions defined by the system to make coding more easy".
The standard functions are also called as library functions or pre-defined functions
or built in functions.
A user can not understand the internal working of the standard functions and can
not be modified but can only use all standard functions.
C language provides a rich set of standard library functions whose definitions have
been written and are ready to use.
The user must include the prototype declarations(header files) to use the standard
library functions.
The some of standard functions are scanf(), printf(), sqrt(), abs(), log(), sin(), pow()
etc.
You can write as many functions as you like in a program as long as there is only one
main ().
As long as these functions are saved in the same file, you do not need to include a
header file. They will be found automatically by the compiler.
Return_type specifies the type of value that the function's return statement
returns.If nothing is returned to the calling function, then data type is void.
function_name is a user-defined function name. It must be a valid C identifier.
Parameter list declares the variables that will receive tha data sent by the
calling function. They serve as input data to the function to carry out the specified
task. Since they represent actual input values, they are often rerred to as formal
parameters.
returnis a keyword used to send the output of the function, back to the calling
function. It is a means of communication from the called function to the calling
function. There may be one or more return statements. When a return is
encountered, the control is transferred to the calling function.
main( )
{
int a, b, c, sum ;
printf( "\nEnter any three numbers " ) ;
scanf( "%d %d %d", &a, &b, &c ) ;
sum = calsum( a, b, c ) ;
printf( "\nSum = %d", sum ) ;
}
(b) The variables a, b and c are called ‘actual arguments’, whereas the variables x, y
and z are called ‘formal arguments’.
(c) Any number of arguments can be passed to a function being called.
(d) However, the type, order and number of the actual and formal arguments must
always be same.
(e) Instead of using different variable names x, y and z, we could have used the same
variable names a, b and c. But the compiler would still treat them as different
variables since they are in different functions.
There are two methods of declaring the formal arguments. The one that we have used
in our program is known as ANSI method and is more commonly used these days.
calsum( int x, int y, int z )
Another method is,
calsum( x, y, z )
I B.Tech C StudyMaterial 4 D.Madhu Babu, M.Tech.
int x, y, z ;
{
// Body of the function
}
This method is known as Kernighan and Ritchie (or just K & R) method.
(f) In the above program, however, we want to return the sum of x, y and z. Therefore,
it is necessary to use the return statement. The return statement serves two
purposes:
1.On executing the return statement it immediately transfers the control back to
the callingprogram.
2. It returns the value present in the parentheses after return, to the calling
program. In
the above program the value of sum of three numbers is being returned.
Example:
fun( )
{
char ch ;
printf( "\nEnter any alphabet " ) ;
scanf( "%c", &ch ) ;
if ( ch>= 65 &&ch<= 90 )
return ( ch ) ;
else
return ( ch + 32 ) ;
}
In this function different return statements will be executed depending on
whether ch is capital or not.
(g) Whenever the control returns from a function some value is definitely returned. If a
meaningful value is returned then it should be accepted in the calling program by
equating the called function to some variable. For example,
sum = calsum( a, b, c ) ;
(j) If the value of a formal argument is changed in the called function, the corresponding
change
does not take place in the calling function. For example,
main( )
{
int a = 30 ;
fun ( a ) ;
printf( "\n%d", a ) ;
}
fun ( int b )
Category of functions:
We have some other type of functions where the arguments and return value may be
present or absent. Such functions can be categorized into:
Example:
The following program illustrates the function with no arguments and no return value.
# include <stdio.h>
main ()
Example:
The following program illustrates the function with arguments and no return value.
# include <stdio.h>
main ()
{
Int a=10,b=20;
Void sum(int a, int b);
Clrscr();
Sum(a,b);
Getch();
}
Example:
The following program illustrates the function with arguments and no return value.
# include <stdio.h>
main ()
{
Int c;
int sum();
Clrscr();
C=Sum();
printf (“\nThe sum of Two numbers is ….:%d” ,c)
Getch();
}
}
Output:
The sum of Two numbers is ….: 30
Example:
The following program illustrates the function with arguments and no return value.
# include <stdio.h>
main ()
{
Int a=10,b=20,c;
int sum();
Clrscr();
C=Sum(a,b);
printf (“\nThe sum of Two numbers is ….:%d” ,c)
Getch();
}
int sum(int a, int b) /* return value */
{
Int c;
C = a + b;
Return ( c );
}
Output:
The sum of Two numbers is ….: 30
1. Call by Value
2. Call by Address(or Reference)
1.Call by Value:
The call-by-value method copies the value of an actual argument into the formal
parameter of the function.
Therefore, changes made by the function to the formal parameters have no effect
on the actual arguments in the calling function.
Example:
# include <stdio.h>
main ()
I B.Tech C StudyMaterial 9 D.Madhu Babu, M.Tech.
{
int a=10, b=20;
void swap (int x, int y); /* function prototype */
printf(“\nBy using Call by Value, Before swapping , values of A and B are :%4d
%4d”,a,b)
swap (a, b); /* values passed */
printf(“\nBy using Call by Value, After swapping , values of A and B are :%4d
%4d”,a,b)
getch();
}
temp = a;
a = b;
b = temp;
}
Output :
By using Call by Value, After swapping , The values of A and B are ……: 10 20
In the above program, the variables a and b are assigned the values of 10 and 20 in the
main. During the execution of the ‘swap’function , the values of aand b are exchanged,
but the values of the actual arguments a and b in the main function remains the same
as prior to the execution of the function call.
Example:
# include <stdio.h>
Void main ()
{
int a=10, y=20;
void swap (int *x, int *y); /* function prototype */
printf(“\nBy using Call by Address,Beforeswapping,values of A and B are:%4d
%4d”,a,b
I B.Tech C StudyMaterial 10 D.Madhu Babu, M.Tech.
swap (&a, &b); /* addresses passed */
printf(“\nBy using Call by Address, After swapping , The values of A and B are …:
%4d
%4d”,a,b
temp = *x;
*x = *y;
*y = temp;
}
Output :
By using Call by Address, After swapping , The values of A and B are ……: 20 10
In the above program, the variables a and b are assigned the values of 10 and 20 in the
main. The values of a and b in main can be changed during the execution of the
‘swap’function by using their addresses which are copied in formal parameters x and y.
Hence the values of a and b in main are 20 and 10(swapped).
As an unsized array:
As a pointer:
Example:
main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf("\n This from message2 function”);
}
message1( )
{
printf( "\n This from message1 function" ) ;
}
A function can be called from other function, but a function cannot be defined in
another function. Thus, the following program code would be wrong, since
message( ) is being defined inside another function, main( ).
main( )
{
printf( "\nThis is main" ) ;
message( )
{
printf( "\nthis is message function" ) ;
}
}
Nested Functions:
Calling one function in another function is called nested functions. We have seen
programs using functions called only from the main() function.
But there are situations, where functions other than main() can call any other
function(s) used in the program.
This process is referred as nested functions. C permits nesting of functions freely
ie.,, main() can call function1, which calls function2 , which calls function3 and so
on. There is no limit as to how deeply functions can be nested.
#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function 1”);
func2();
printf (“\n Again inside function 1”);
}
void func2()
{
printf (“\n Inside function 2”);
}
Output:
Inside main function
Inside function 1
Inside function 2
Again inside function 1
Again inside main function
Recursion:
In C, it is possible for the functions to call themselves. When a function call itself is
called Recursion.
A function is called ‘recursive’ if a statement within the body of a function calls the
same function. Recursion functions must have terminating condition to avoid
infinite loop.
Recursion function can be used to solve problems where the solution is expressed
in terms of successively applying the same solution to subsets of the problem.
Suppose we want to calculate the factorial value of an integer. As we know, the factorial
of a number is the product of all the integers between 1 and that number. For example,
4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for
factorial. Thus factorial of a number can be expressed in the form of itself. Hence this
can be programmed using recursion.
Example :
main( )
{
int n;
long int f ;
printf( "\nEnter N value ……..: " ) ;
scanf( "%d", &n ) ;
fact = rec_factorial( n ) ;
printf( "Factorial of %4d is …: %4ld",n, f ) ;
getch();
}
Output…:
In case the value of n is 5, main( ) would call rec_factorial( ) with 5 as its actual
argument, and rec_factorial( ) will send back the computed value. But before sending the
I B.Tech C StudyMaterial 16 D.Madhu Babu, M.Tech.
computed value, rec_factorial( ) calls rec_factorial( ) and waits for a value to be returned.
These recursive invocations end finally when the last invocation gets an argument value
of 1, which the preceding invocation of rec_factorial( ) now uses to calculate its own fact
value and so on up the ladder. So we might say what happens is,
Storage classes:
Storage classes are used to define the scope (visibility) and life-time of variables
and functions.
Every variable and function in C has two attributes: type and storage class.
There are basically two kinds of locations in a computer where a value of variable
may be kept— Memory and CPU registers.
The variable’s storage class that determines in which of these two locations the
value is stored.
Moreover, a variable’s storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e.
the default initial value).
(c) What is the scope of the variable; i.e. in which functions the value of the variable
would be
available.
(d) What is the life of the variable; i.e. how long would the variable exist.
main( )
{
auto int i, j=0 ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be... : 1211 0
1) register int x;
2) register int counter;
The declaration register i; is equivalent to register int i;
The features of a variable defined to be of register storage class are as under:
Storage - CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which the variable is defined.
Life - Till the control remains within the block in which the variable is defined.
For example
extern int i,j;
The features of a variable whose storage class has been defined as external are as
follows:
Storage − Memory.
Default initial value− Zero.
Scope− Global.
Life − As long as the program’s execution doesn’t come to an end.
# include <stdio.h>
extern int a = 1, b = 2, c = 3;
Variables defined outside a function have external storage class, even if the
keyword extern is not used. Such variables cannot have auto or register storage
class.
A complete summarized table to represent the lifetime and visibility (scope) of all the
storage class specifier is as below:
Introduction to Files
Types of Files
When dealing with files, there are two types of files you should know about:
I B.Tech C StudyMaterial 21 D.Madhu Babu, M.Tech.
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
The content of Text file is readable
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
File Operations
In C, you can perform four major operations on files, either text or binary:
4. Closing a file
You can create, open, read, and write to files by declaring a pointer of type FILE, and
use the fopen() function:
FILE *fptr
fptr = fopen(filename, mode);
FILE is basically a data type, and we need to create a pointer variable to work with it
(fptr). For now, this line is not important. It's just something you need when working
with files.
To open a file, use the fopen() function, which takes two parameters:
Mode Description
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file.
However, if the file does not exist, it will create one for you:
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
We must open a file before it can be read, write, or update. The fopen() function is
used to open a file.
Example:
FILE *fp ;
I B.Tech C StudyMaterial 23 D.Madhu Babu, M.Tech.
fp = fopen("SampleTextFile.c","r") ;
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.
The file read operation in C can be performed using functions fscanf() , fgets() and
fgetc.
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return
value is the character read, or in case of any error, it returns EOF.
The following function allows to read a string from a stream −
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("SampleTextFile.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Writing a File
The function fputc() writes the character value of the argument c to the output
stream referenced by fp.
It returns the written character written on success otherwise EOF if there is an
error.
You can use the following functions to write a null-terminated string to a stream −
The function fputs() writes the strings to the output stream referenced by fp.
It returns a non-negative value on success, otherwise EOF is returned in case of
any error.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a
string into a file.
Example
FILE *fp;
// Create a file
fp = fopen("SampleTextFile.txt", "w");
// Close the file
fclose(fp);
Fclose(fp);