0% found this document useful (0 votes)
242 views11 pages

Unit 5 Introduction To Programming

Uploaded by

shabanasarwani
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)
242 views11 pages

Unit 5 Introduction To Programming

Uploaded by

shabanasarwani
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/ 11

UNIT V

Introduction to Functions, Function Declaration and Definition, Function call, Return Types and
Arguments, modifying parameters inside functions using pointers, arrays as parameters. Scope
and Lifetime of Variables, Basics of File Handling
Introduction to Function:
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main function, and programs can define additional functions also.
Functions are reusable components.
Function also called as a method or a sub-routine or a procedure, etc.
There are basically two types of function depending on who developed
1. Library functions
2. User defined functions
Library functions:
Library functions are also called as predefined functions or built in functions. Library functions
developed by language authors. We can simply call them.
printf(), scanf(), clrscr(), and strcmp() are examples of library functions.
User defined functions:
User defined functions are developed by the user.
In order to make use of a user-defined function, we need to establish three elements that are
related to functions.
1. Function definition.
2. Function declaration.
3. Function call
Function definition:
Function definition also called function implementation.
Syntax:
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming language consists of a function header and a function
body. Here are all the parts of a 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. The function name and the parameter
list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. Parameters are optional;
that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.
Example:
Following is the source code for a function called max.:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
int largest; /* local variable declaration */
if (num1 > num2)
{
largest = num1;
}
else
{
largest = num2;
}
return largest;
}
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The
function declaration also called function prototype.
Syntax:
return_type function_name( parameter list );
Example:
int max(int num1, int num2);
Parameter names are optional in function declaration, so following is also valid declaration:
int max(int, int);
Calling a Function:
Function calling also called function invoking.
Syntax:
function_name( argument1,… );
When a program calls a function, program control is transferred to the called function.
Then following conditions are tested:
1. Function name: Function name should be matched.
2. Number of parameters: The number arguments should equal to number of parameters.
3. Type of parameters: The type of arguments and parameters should be same.
When numbers of parameters are zero, then third condition not tested. If all conditions are true a
called function performs defined task and when its return statement is executed or when its
function ending closing brace is reached, it returns program control back to the main function.
//example program on function
#include<stdio.h>
#include<conio.h>
void main()
{
int max(int num1,int num1);//function declaration
int a,b,big;
clrscr();
printf("Enter two integer numbers:");
scanf("%d%d",&a,&b);
big=max(a,b);//function call
printf("The big number is:%d",big);
getch();
}
int max(int num1,int num2) // function definition
{
int largest; //local variable
if(num1>num2)
{
largest=num1;
}
else
{
largest=num2;
}
return largest; // return statement
}
Output:
Enter two integer numbers: 100 200
The big number is:200

Return Types and Arguments:


A function, depending on whether arguments are present or not and whether a value is returned
or not, may belong to one of the following categories:
Category 1: Functions with no arguments and no return values.
Category 2: Functions with arguments and no return values.
Category 3: Functions with arguments and one return value.
Category 4: Functions with no arguments but return a value.
Category 5: Functions that return multiple values.
No Arguments and No Return Values:
When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from the
called function.

Example:
void printline (void);

Arguments But No Return Values:


When a function has arguments, it receives data from the calling function. Similarly, when it
does not return a value, the calling function does not receive any data from the called function.
Examples:
void printline(char ch)
void value(float p, float r, int n)

Arguments with Return Values:


When a function has arguments, it receives data from the calling function. Similarly, when it
returns a value, the calling function receives data from the called function.
Example:
int max(int num1,int num1);
No Arguments but Returns a Value
When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it returns a value, the calling function receives data from the called function.
Example:
int max( );
Function1() No arguments Function2 ()
{ {
………… …………
Function2() …………
………… …………
Function result return (e)
}
}

}
Fig. One way communication between functions.

Functions that Return Multiple Values:


Below are the methods to return multiple values from a function in C:
1. By using pointers.
2. By using structures.
3. By using Arrays.
Modifying parameters inside functions using pointers
Types of arguments:
1. Call by value: This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside the function have
no effect on the argument.
2. Call by reference: This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument used in the
call. This means that changes made to the parameter affect the argument.
// Modifying parameters inside functions using pointers
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int a,b;
clrscr();
printf("Enter two integer values:");
scanf("%d%d",&a,&b);
swap(&a,&b);/* call-by-reference*/
printf("\n from main function");
printf("\n After swapping:");
printf("\n a value is %d",a);
printf("\n b value is %d",b);
getch();
}

void swap(int *a,int *b)


{
int temp;
temp=*a;
*a=*b;
*b=temp;
printf("from swap function");
printf("\na value is :%d",*a);
printf("\nb value is :%d",*b);
}
Output:

Arrays as parameters:
Like the values of simple variables, it is also possible to pass the values of an array to a function.
To pass a one-dimensional an array to a called function, it is sufficient to list the name of the
array, without any subscripts, and the size of the array as arguments.
For example, the call largest(a,n) will pass the whole array a to the called function. The called
function expecting this call must be appropriately defined.
The largest function header might look like:
float largest(float array[ ], int size)
The function largest is defined to take two arguments, the array name and the size of the array to
specify the number of elements in the array.
The declaration of the formal argument array is made as follows: float array[ ]; The pair of
brackets informs the compiler that the argument array is an array of numbers. It is not necessary
to specify the size of the array here.
Let us consider a problem of finding the largest value in an array of elements.
The program is as follows:
// program on arrays as parameters
#include<stdio.h>
#include<conio.h>
main( )
{
float largest(float a[ ], int n);
float value[4] = {2.5,-4.75,1.2,3.67};
clrscr();
printf(“%f\n”, largest(value,4));
getch();
}
float largest(float a[], int n)
{
int i; float max;
max = a[0];
for(i = 1; i < n; i++)
{
if(max < a[i])
{
max = a[i];
}
}
return (max);
}
Output:
The largest value is:3.67
Scope and Lifetime of Variables:
Scope:
It determines the part of the program where the variable is visible or available for use.
There are two scopes namely
 Global scope
 Local scope
Global Scope:
Any variable declared above the main function is visible or available from its point of
declaration to the end of the program.
Local Scope:
Any variable declared within a block is visible or available only within that block.
Lifetime: The time for which the variable holds a valid memory address with a valid value
irrespective of, if someone has access to it or not.
Or
The time duration for which a variable is alive called lifetime of variable.
//example program on scope and life time of variable
#include<stdio.h>
//#include<conio.h>
int a;//global variable
void main()
{
int sum(int num1);//function declaration
int b,add;//local variable
// clrscr();
printf("Enter two integer numbers:");
scanf("%d%d",&a,&b);
add=sum(b);//function call
printf("The sum of two number is:%d",add);
// getch();
}
int sum(int num1) // function definition
{
int add1; //local variable
//printf("%d",b); // Error
Add1=a+num1;
return add1; // return statement
}
Storage class:
Storage class defines the following information for a variable.
 Location of the variable where it is stored
 Initial value of the variable
 Scope of the variable
 Lifetime of the variable
There are four storage classes supported in C Language. They are
1. Automatic storage class
2. External storage class
3. Static storage class
4. Register storage class.

Automatic External Static Register


 1. It is stored in 1. It is stored in the 1. It is stored in the 1. It is stored in the CPU
the memory of the memory of the memory of the registers.
computer. computer. computer.
 The default value The default value for a The default value The default value for a
for a variable variable declared with for a variable variable declared with
declared with this this storage class is declared with this this storage class is
storage class is 0(zero). storage class is garbage value.
garbage value. 0(zero).
 Scope of the Scope of the variable is  Scope of the Scope of the variable is
variable is within global. variable is within within the block where it
the block where it  the block where it is declared.
is declared. is declared.
 It is active and It is active and alive  It is active and It is active and alive only
alive only in that until the end of the alive only in that in that block.
block. program. block.
 The key word The key word extern is  The key word The key word register is
auto is used to used to declare the static is used to used to declare the
declare the variable as external declare the variable variable as register
variable as storage class. as static storage storage class.
automatic storage class. 
class.
 E.g.,  E.g.,  E.g.,  E.g.,
auto int i; extern int i; static int i; register int i;

Basics of File Handling:


A file is a place on the disk where a group of related data is stored.
Following are some important file functions.

Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file
in standard I/O is:

ptr=fopen("fileopen","mode")
Example:
fopen("E:\\cprogram\program.txt","w");

Opening Modes
File Mode Meaning of Mode During Inexistence of file

r Open for reading. If the file does not exist, fopen() returns NULL.

If the file exists, its contents are overwritten. If the


w Open for writing.
file does not exist, it will be created.

Open for append. i.e, Data is


a If the file does not exists, it will be created.
added to end of file.

Open for both reading and


r+ If the file does not exist, fopen() returns NULL.
writing.

Open for both reading and If the file exists, its contents are overwritten. If the
w+
writing. file does not exist, it will be created.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().

fclose(ptr);
// program which copies contents from one file two another file.
#include<conio.h>
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);


fclose(fptr1);
fclose(fptr2);
return 0;
}

Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt

You might also like