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

Derivatives Functions

This document discusses file handling in C programming. It defines a file as a permanent storage space on a disk that can be accessed through library functions. There are two main types of files - sequential files where data must be read sequentially, and random access files where any record can be read directly. It also describes how to open, read, write, close and perform other operations on files using functions like fopen(), fclose(), fread(), fwrite() and more.

Uploaded by

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

Derivatives Functions

This document discusses file handling in C programming. It defines a file as a permanent storage space on a disk that can be accessed through library functions. There are two main types of files - sequential files where data must be read sequentially, and random access files where any record can be read directly. It also describes how to open, read, write, close and perform other operations on files using functions like fopen(), fclose(), fread(), fwrite() and more.

Uploaded by

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

FILE HANDLING

FILE HANDLING
• PROBLEM:-if we need same data to be processed again
and again, we have to enter it again and again and if volume
of data is large, it will be time consuming process.
• SOLUTION:-data can be permanently stored, a program can
read it directly at a high speed.
• The permanent storage space on a disk is called FILE.
• FILE is a set of records that can be accessed through the set
of library functions.
FILE TYPES
1.SEQUENTIAL FILE:-in this data is kept permanently. If we want
to read the last record of file then we need to read all the
records before that record.it means if we wan to read 10th
record then the first 9 records should be read sequentially for
reaching to the 10th record.

2.RANDOM ACCESS FILE:- in this data can be read and modified


randomly. If we want to read the last record of the file, we can
read it directly. It takes less time as compared as sequential
file.
Text Files vs. Binary Files
• Text files are human readable files. They are
universal and can be edited with many
different programs such as NOTEPAD.
– contains ASCII codes only
• Binary files are not human readable. They
contain information encoded into the
numbers which make up the file which are
ultimately turned into ones and zeros, thus
the name “binary.”
HOW TO DEFINE A FILE
Before using a file in a program,we must open it,which
establishes a link between the program and the operating
system.A file must be defined as:-
FILE *fp;

structure file pointer


(user data type)
where FILE is the data structure which is included in the header
file,stdio.h and fp is declared as a pointer which contains the
address of a character which is to be read.
Operation on a file
fp = fopen (“ABC.txt”, “r”);
Here fp =file pointer
fopen= function to open a file
ABC.txt=name of the file
r=mode in which file is to be opened
fopen is a function which contains two arguments:-
1. File name ABC.txt
2. Mode in which we want to open the file.
3. Both these are of string types.
fopen():-
• This function loads the file from disk to memory and
stores the address of the first character to be read in
the pointer variable fp.
• If file is absent,it returns a NULL pointer variable.

fclose(fp):- the file which is opened need to be closed


and only can be done by library function fclose.
File opening modes

• If you are going to handle binary files then you will use below mentioned access modes
instead of the above mentioned:
• "rb", "wb", "ab", "ab+", "a+b", "wb+", "w+b"
void main()
{
FILE *fp;
fp=fopen(“data.txt”,”r”);
If(fp = = NULL)
{
printf(“cannot open file”);
}
getch();
}
Closing a file
• To reopen it in some other mode
• To prevent any misuse with the file
• To make the operations you have performed
on the files successful.
To close a file, we must use function fclose()
Syntax:
int fclose(FILE *stream);
fclose()
• It closes the named stream. We can pass
pointer variable that points to a file to be
closed. All buffers associated with the stream
are flushed before closing.
• On success, fclose() returns 0 otherwise, it
returns end of function (EOF).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
clrscr();
fptr=fopen("a.txt",“w");
if(fptr==null)
printf("\n file cannot be opened for creation");
else
printf("\n file created successfully");
fclose(fptr);
}
Binary modes:-

• wb(write):-it opens a binary file in write mode.


fp=fopen(“data.dat”,”wb”);
Here data.dat file is opened in binary mode for writing.

• rb(read):-it opens a binary file in read mode.


fp=fopen(“data.dat”,”rb”);
Here data.dat file is opened in binary mode for reading.

s
Reading from a file
Different functions to read a char are fgetc and getc. Both
perform similar functions and have the same syntax.

ch = fgetc (fp);

char type function file pointer


variable name
fgets() or gets():-used to read strings from a file and copy
string to a memory location which is referenced by array.
fgets(str, n, fptr);

array of chars max length file pointer


Writing chars to a file
• fputc() or putc():-both these fuction write the character
in the file at the position specified by pointer.
putc (c, fp);

function character file pointer


type variable
The file pointer automatically moves 1 position forward after
printing characters in the file.
Read &write char into file and prints them
#include<conio.h>
#include<conio.h>
#include<stdio.h>
void main()
void main()
{
{
FILE *fptr;
FILE *fptr;
char c;
char c;
clrscr();
clrscr();
fptr=fopen("a.txt","r");
fptr=fopen("a.txt","w");
printf("the line of text is");
printf("Enter the line of text,press ^z to
while((c=getc(fptr))!EOF) stop ");
{ while((c=getchar())!EOF)
printf("%c",c); {
} putc(c,fptr);
fclose(fptr); }
getch(); fclose(fptr);
} }
Program to understand use of fgetc()
main( ) EOF:-END OF FILE
{
FILE *fptr;
char ch; EOF is an integer value sent
fptr= fopen(“rec.dat”,”r”); to prog.by OS. it’s value is
if(fptr = = NULL) predefined to be -1 in
printf(“file doesn’t exist”); STDIO.H, No char with the
else
same value is stored on
{
disk. while creating file, OS
while( ch = fgetc(fptr) !=EOF)
detects that last character
printf(“%c”,ch);
to file has been sent, it
}
transmits EOF signal.
fclose(fptr);
}
Writing to file using fputs (sptr, fptr)
main() else
{ {
FILE *fp;
printf(“the string is “);
char name[20],arr[50];
printf(“enter the file name”); gets(arr);
scanf(“%s”,name); fputs(arr,fp);
fp=fopen(name,”w”); }
if(fp = = NULL) fclose(fp);
{
}
printf(“file can’t be opened”);
exit(0);
}
• fscanf( ):- it is used to read to any type of variable
i.e.,char,int,float,string
fscanf(fp,”%c”,&ch);

file pointer control char type


string variable
fscanf(fp,”%c%d%f”,&a,&b,&c);
We write stdin, this func call will work similar to simple scanf
Because stdin means standard i/p i.e.keyboard.
fscanf(stdin,”%c”,&ch);
Is equivalent to
scanf(“%c”,&ch);
#include<conio.h>
void main()
{
FILE *fptr;
char name[10];
int sal;
fptr=fopen(“rec.dat”,”r”);
fscanf(fptr,”%s%d”,name,&sal);
while(!feof(fptr))
{
printf(“%s%d”,name,sal);
fscanf(fptr,”%s%d”,name,&sal);
}
fclose(fptr);
getch();
}
• fprintf():- it is used to print chars,numbers or strings in a
file.
fprintf (fp,“%d”,a);
With this function,we can print a no. of variables with single call.
fprintf (fp,”%c %d %d”,a,b,c);

We write stdout,this func call will work similar simple printf


Because stdout means standard o/p i.e.keyboard.
fprintf(stdout,”%c”,ch);
Is equivalent to
printf(“%c”,ch);
Program for fprintf()
main()
{
FILE *fp;
char name[10];
fp=fopen(“rec.dat”,”w”);
printf(“enter your name”);
scanf(“%s”,name);
fprintf(fptr,”%s”,name);
fclose(fp);
}
• fread():-reads a block(array or structure)from a file.
fread( ptr, m, n ,fptr);

address of size of no.of arrays file pointer


array/structure array/structure

• fwrite():-writes a block(array or structure)from a file.


fread( ptr, m, n ,fptr);

address of size of no.of arrays file pointer


array/structure array/structure
#include<conio.h>
Prog for fread()
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student st;
file *fptr;
fptr=fopen("d.txt","r");
clrscr();
fread(&st,sizeof(st),1,fptr);
printf("roll number is %d",st.rollno);
printf("name is %s",st.name);
fclose(fptr);
getch();
}
#include<conio.h>
Prog for fwrite()
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student st;
file *fptr;
fptr=fopen("d.txt","w");
clrscr();
printf("enter roll number");
scanf("%d",&st.number);
printf("enter name");
gets(st.name);
fwrite(&st,sizeof(st),1,fptr);
fclose(fptr);
getch();
}
• getw():-it is an integer oriented function.it is used to
read an integer from file in which numbers are stored.
a=getw(fptr);

int type var fun name int type var

• putw():-it prints a number in the file.


putw( a, fptr);

lib fun int type var file pointer


Prog for getw()
#include<conio.h>
void main()
{
file *fptr;
int i,n;
clrscr();
fptr=fopen("b.txt","r");
printf("\n the number are")
for(i=1;i<=10;i++)
{
n=getw(fptr);
printf("%d\t",n);
}
fclose(fptr);
getch();
}
Prog for putw()
#include<conio.h>
void main()
{
file *fptr;
int i,n;
clrscr();
fptr=fopen("b.txt","w");
for(i=1;i<=10;i++)
{
printf("enter number");
scanf("%d",&n);
putw(n,fptr);
}
fclose(fptr);
getch();
}
• fseek():-it is used for setting the file position pointer at the specified
byte.
fseek( FILE *fp,long offset,int origin);

file pointer long int can no.of bytes skipped


be +ve/-ve backward(-ve)
forward(+ve)
Constant Value position
SEEK_SET 0 Beginning of file
SEEK_CUR 1 Current position
SEEK_END 2 End of file
EXAMPLE

fseek(p,10L,0);
origin is 0,means that displacement will be relative to
beginning of file, so position pointer is skipped 10 bytes
forward from beginning of file.2nd argument is long integer so
L is attached with it.
fseek(p,8L,SEEK_SET);
position pointer is skipped 8 bytes forward from beginning of
file.
fseek(p,-6L,SEEK_END);
position pointer is skipped 6 bytes backward from the end of
file.
Replace a char x by char y
main()
{
FILE *fp;
char temp,name[];
printf(“enter name of file”);
scanf(“%s”,name);
fp=fopen(“name”,”r”);
while((temp=getc(fptr))!=EOF)
{
if(temp= =‘x’)
{
fseek(fp, -1,1);
putc(‘y’,fp);
}
}
fclose(fp);
}
ftell():-it is required to find the current location of the file pointer
within the file
ftell(fptr);
Fptr is pointer for currently opened file.
main()
{
FILE *fp;
char ch;
fp=fopen(“text”,”r”);
fseek(fp,241,0);
ch=fgetc(fp);
while(!feof (fp))
{
printf(“%c”,ch);
printf(“%d”,ftell(fp));
ch=fgetc(fp);
}
fclose(fp);
}
Rewind():-it is used to move the file pointer to the beginning of the given
file.
rewind(fptr);
main()
{
FILE *fp;
fp=fopen(“stu.dat”,”r”);
if(fp==NULL)
{
printf(“file can not open”);
exit(0);
}
printf(“position pointer %d”,ftell(fp));
fseek(fp,0,2);
printf(“position pointer %d”,ftell(fp));
rewind(fp);
fclose(fp);
}
• ferror():-it is used for detecting error in the file
when file read write operation is carried out.
It returns the value nonzero if an error occurs
otherwise returns zero value.
ferror(fptr);
WAP that writes the contents entered by user at runtime to a file, then read
the contents of file using function fgetc() and fputc()
void main()
{
FILE *fp;
int c;
clrscr();
fp=fopen(“ABC.doc”,”w”);
if(fp==NULL)
{
printf(“file not opened in write mode”);
getch();
exit(0);
}
printf(“file opened successfully, enter ctrl +z to exit\n”);
while(c=getchar()!=EOF)
{
fputc(c,fp);
}
fclose(fp);
fp=open(“ABC.doc”,”r”);
if(fp==NULL)
{
printf(“file not opened in read mode”);
getch();
exit(0);
}
printf(“file opened for reading”);
c=fgetc(fp);
while(c!=EOF)
{
printf(“%c”,c);
c=fgetc(fp);
}
fclose(fp);
getch();
}
CSE101-lec#12
• Recursive function(or Recursion)
• Mathematical functions in C(<math.h> header
file)

©LPU CSE101 C Programming


Outline
• Recursion
• Examples of recursion
– Finding factorial of a number
– Finding sum of all numbers from 1 to n
– Printing n terms of Fibonacci series using
recursion
• Recursion Vs Iteration
• Mathematical functions in C

©LPU CSE101 C Programming


Recursion
• It is a process in which function calls itself again
and again and the function which is called is
known as recursive function
• Recursion is supported with two cases: base
case and recursive case
• Base case is one which helps to stop the
recursion once the required operation is done
• Recursive case is one which keeps on repeating
and function will keep on calling itself

©LPU CSE101 C Programming


Example
int fact(int n)
{
if (n < = 1) // base case( Here the recursion will stop)
return 1;
else
return n*fact(n-1); //recursive case where fact() is calling itself
}

©LPU CSE101 C Programming


Recursion example (factorial)
Fin a l va lue = 120
5! 5!
5! = 5 * 24 = 120 is re turn ed
5 * 4! 5 * 4!
4! = 4 * 6 = 24 is re turne d
4 * 3! 4 * 3!
3! = 3 * 2 = 6 is re tu rn e d
3 * 2! 3 * 2!
2! = 2 * 1 = 2 is re turne d
2 * 1! 2 * 1!
1 re turne d
1 1

( a ) Se q u en c e o f re c ursive c a lls. ( b ) Va lue s re turne d fro m e a c h re cu rsive c a ll.

©LPU CSE101 C Programming


Program example 1-Write a program to find the factorial of a
number using recursion(or recursive function)
#include <stdio.h>
long long int factorial(int);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %lld", n, factorial(n));
return 0;
}
long long int factorial(int n)
{
if (n <=1)
return 1;
else
return n*factorial(n-1);
}

©LPU CSE101 C Programming


Program example 2-Write a program to find the sum of all
numbers from 1 to n using recursion(or recursive function)

#include <stdio.h>
int addNumbers(int n);
int main()
{
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d",addNumbers(num));
return 0;
}
int addNumbers(int n)
{
if(n == 0)
return n;
else
return n + addNumbers(n-1);
}

©LPU CSE101 C Programming


Recursion example-3 (Fibonacci series)
• What is Fibonacci series: …??
• 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1)+fibonacci( n – 2 );
}

©LPU CSE101 C Programming


Recursion example (fibonacci)
• Set of recursive calls to fibonacci() function

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

©LPU CSE101 C Programming


Program example 3-WAP to display n terms of Fibonacci series using
recursion(or recursive function)
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i;
printf("\n Enter number of terms you want to print:");
scanf("%d",&n);
printf("Fibonacci series\n");
for(i=0;i<n;i++)
{
printf("%d\n", Fibonacci(i));
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

©LPU CSE101 C Programming


Recursion vs. Iteration

©LPU CSE101 C Programming


Rules for recursive function
1. In recursion, it is essential to call a function itself
2. Only the user defined function can be involved
in the recursion. Library function cannot be
involved in recursion because their source code
cannot be viewed
3. A recursive function can be invoked by itself or
by other function.
4. To stop recursive function, it is necessary to have
a proper base case, otherwise infinite recursion
can happen
5. main() function can be invoked recursively.

©LPU CSE101 C Programming


Math Library Functions(or
Mathematical functions in C)
• Math library functions
– perform common mathematical calculations
– #include <math.h>
• Format for calling maths functions
– functionName( argument );
• If multiple arguments, use comma-separated list
• Example:
printf( "%.2f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of its argument
• All math functions return data type double
– Arguments may be constants, variables, or expressions

©LPU CSE101 C Programming


Math Library Functions
Function Description Example
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0

exp( x ) exponential function ex exp( 1.0 ) is 2.718282


exp( 2.0 ) is 7.389056
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
(base e)
log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( x ) absolute value of x fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
integer not less than x
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
integer not greater than x
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0
fmod( x, y ) remainder of x/y as a fmod( 13.657, 2.333 ) is
1.992
floating point number
sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0
(x in radians)
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0
(x in radians)
©LPU CSE101 C Programming
Math Library Functions: pow()
 The power function, pow(x,y), calculates xy; that is, the
value of
pow(x,y) = xy.
 pow(2,3)= 2³ = 8.0 and pow(2.5,3) = 15.625.
 The function pow is of the type double or that the function
pow returns a value of the type double.
 x and y are called the parameters (or arguments) of the
function pow.
 Function pow has two parameters.

©LPU CSE101 C Programming


sqrt()
 The square root function, sqrt(x),
calculates the non-negative square root of x for x >= 0.0
sqrt(2.25) is 1.5
sqrt(25) is 5.0
 The function sqrt is of the type double and has only one
parameter.

©LPU CSE101 C Programming


fabs()
• fabs calculates the absolute value of a float
argument.
fabs(2.25) is 2.25
fabs(-25.0) is 25.0
The function fabs is of the type double
and has only one parameter.

©LPU CSE101 C Programming


floor()
 The floor function, floor, calculates the largest
whole number that is not greater than x.
floor(48.79) is 48.0
floor(48.03) is 48.0
floor(47.79) is 47.0
 The function floor is of the type double and has
only one parameter.

©LPU CSE101 C Programming


ceil()
 The ceil function, ceil, calculates the smallest
whole number that is not less than x.
ceil(48.79) is 49
ceil(48.03) is 49
ceil(47.79) is 48
 The function ceil is of the type double and has
only one parameter.

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Program example
#include<stdio.h>
#include<math.h>
int main()
{
double x=9.0,y=8.0,z=7.0;
printf("\nLog value is:%lf",log(x));
printf("\nLog value with base 10 is:%lf",log10(x));
printf("\nExponential value is:%lf",exp(x));
printf("\n Ceil value is:%lf",ceil(8.94));
printf("\n Floor value is:%lf",floor(2.34));
printf("\n Power:%lf",pow(3.0,2.0));
printf("\n Floating absolute is:%lf",fabs(-2.9));
printf("\n Square root value is:%lf",sqrt(9));
printf("\n Sin:%f,cos:%f,tan:%lf",sin(x),cos(y),tan(z));
printf("\n fMod:%f",fmod(2.0,1.5));
return 0;

©LPU CSE101 C Programming


Q1
What is the output of the following code?
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(5);
return 0;
}
A. 5
B. 1
C. 5 4 3 2 1 0
D. 5 4 3 2 1

©LPU CSE101 C Programming


Q2
Predict output of following program
#include <stdio.h>
int fun(int n)
{
if (n == 4)
return n;
else return 2*fun(n+1);
}
int main()
{
printf("%d ", fun(2));
return 0;
}

A. 4
B. 8
C. 16
D. 10

©LPU CSE101 C Programming


Q3
Consider the following recursive function fun(x, y). What is
the value of fun(4, 3)
int fun(int x, int y)
{
if (x == 0)
return y;
return fun(x - 1, x + y);
}

A. 13
B. 12
C. 9
D. 10

©LPU CSE101 C Programming


Q4
What does the following function print for n = 25?
void fun(int n)
{
if (n == 0)
return;
printf("%d", n%2);
fun(n/2);
}

A. 11001
B. 10011
C. 11111
D. 00000

©LPU CSE101 C Programming


CSE101-lec#13
• Storage Classes and Scope Rules

©LPU CSE101 C Programming


Outline
• Storage Classes
– auto
– static
– extern
– register
• Scope Rules

©LPU CSE101 C Programming


Storage Classes
• Storage Classes are used to describe the features of a
variable. These features basically include the scope, visibility
and life-time which help us to trace the existence of a
particular variable during the runtime of a program.
• Storage class specifies four things-
I. Storage location: Where the variable will be stored?[ In
memory /or CPU register]
II. Scope: Block in which the variable is accessible.
III. Lifetime: How long would the variable exist?
IV. Default initial value: What will be the initial value of the
variable, if initial value is not specifically assigned ?

©LPU CSE101 C Programming


Storage Classes: Auto
• Automatic storage
– auto int x, y;
– It is the default storage class for a local variable
– This is the default storage class for all the variables
declared inside a function or a block
⮚ Storage − Memory(RAM).
⮚ Default initial value − An unpredictable value, which is
often called a garbage value.
⮚ Scope − Local to the block in which the variable is
defined.
⮚ Lifetime − Till the control remains within the block in
which the variable is defined.

©LPU CSE101 C Programming


Program example-auto storage class
#include<stdio.h>
void func1()
{
auto int a=10; // Local variable of func1()
printf("\n a=%d",a);
}
void func2()
{
auto int a=20; //Local variable of func2()
printf("\n a=%d",a);
}
int main()
{
auto int a=30;//Local variable of main()
func1();
func2();
printf("\n a=%d",a);
return 0;
}

©LPU CSE101 C Programming


Storage Classes: Register
• register: tries to put variable into high-speed
registers.
– register int counter = 1;

⮚ Storage - CPU registers.


⮚ Default initial value - Garbage value.
⮚ Scope - Local to the block in which the variable is
defined.
⮚ Lifetime - Till the control remains within the block in
which the variable is defined.

©LPU CSE101 C Programming


More points in relation to register storage class

• This storage class declares register variables which have the same
functionality as that of the auto variables. The only difference is that the
compiler tries to store these variables in the register of the
microprocessor if a free register is available.
• This makes the use of register variables to be much faster than that of the
variables stored in the memory during the runtime of the program. If a
free register is not available, these are then stored in the memory only.
• Usually few variables which are to be accessed very frequently in a
program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be
noted here is that we cannot obtain the address of a register variable
using pointers.

©LPU CSE101 C Programming


Program example-register storage class
#include<stdio.h>
int main()
{
register int i; // i will be used frequently so, it can be given register storage class
for(i=1;i<=20;i++)
{
printf("\n%d",i);
}
return 0;
}

©LPU CSE101 C Programming


Storage Classes: Static
• Static storage
⮚ Storage − Memory(RAM).
⮚ Default initial value − Zero.
⮚ Scope − Local to the block in which the variable is
defined.
⮚ Life time − variable will retain its value throughout the
program

©LPU CSE101 C Programming


More points in relation to static storage class

• Static variables have a property of preserving their value even


after they are out of their scope! Hence, static variables
preserve the value of their last use in their scope.
• So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is
allocated because they are not re-declared.
• Their scope is local to the function to which they were
defined. Global static variables can be accessed anywhere in
the program. By default, they are assigned the value 0 by the
compiler.

©LPU CSE101 C Programming


Program example-static storage class
#include<stdio.h>
void function();
int main()
{
Output:
function();
function(); Value of a:10, Value of b:10
function(); Value of a:10, Value of b:11
return 0;
Value of a:10, Value of b:12
}
void function()
{
int a=10;
static int b=10;
printf("\n Value of a:%d, Value of
b:%d",a,b);
a++;
b++;
}

©LPU CSE101 C Programming


Storage Classes: extern
Extern storage class simply tells us that the variable is
defined elsewhere and not within the same block
where it is used. Basically, the value is assigned to it in
a different block and this can be overwritten/changed
in a different block as well
⮚ Storage − Memory(RAM).
⮚ Default initial value − Zero.
⮚ Scope − Global.
⮚ Life − As long as the program’s execution doesn’t come
to an end.

©LPU CSE101 C Programming


More points in relation to extern storage
class
• extern variable is nothing but a global variable
initialized with a legal value where it is declared in
order to be used elsewhere. It can be accessed within
any function/block.
• Also, a normal global variable can be made extern as
well by placing the ‘extern’ keyword before its
declaration/definition in any function/block.
• This basically signifies that we are not initializing a new
variable but instead we are using/accessing the global
variable only. The main purpose of using extern
variables is that they can be accessed between two
different files which are part of a large program.

©LPU CSE101 C Programming


Program example 1-extern storage class
External variable in the same file
#include<stdio.h>
void first();
int main()
{
extern int x; /* declaration in main() */
printf("\nx=%d",x); // x is used before its definition[Possible because of extern]
first();
printf("\nx=%d",x);// Changes done by first are visible here
return 0;
}
void first()
{
extern int x; /* declaration in first() */
printf("\nx=%d",x); // x is used again before its definition[Possible because of extern]
x=x+10;
}
int x=10; /* definition of external variable, here x is global variable */

©LPU CSE101 C Programming


Program example 2-extern storage class
External variable in different file
extern1.c file
extern2.c file
#include<stdio.h>
void print()
#include"extern2.c" {
//Global variable declared in extern1.c extern int x;//Taking reference of
int x=30; global variable in different file or
int main() Declaration
{ printf("%d\n",x);
x=x+10;
print();
}
printf("%d",x);//Changes done by extern2.c
//Output:
file are also reflected
30
}
40

©LPU CSE101 C Programming


Summary

©LPU CSE101 C Programming


Scope Rules
• The scope of a variable is the portion of a
program where the variable has meaning
(where it exists).
• A global variable has global (unlimited) scope.
• A local variable’s scope is restricted to the
function that declares the variable.
• A block variable’s scope is restricted to the
block in which the variable is declared.

©LPU CSE101 C Programming


Local variables
• Parameters and variables declared inside the
definition of a function are local.
• They only exist inside the function body.
• Once the function returns, the variables no
longer exist!

©LPU CSE101 C Programming


Example-local variable
#include<stdio.h>
void function();
int main()
{
int a=1,b=2;
printf("\n a is:%d,b is:%d",a,b);//a,b are local variables of main()
function();
return 0;
}
void function()
{
int c=3;
printf("\n Value of c is:%d",c);// c is a local variable of function
}

©LPU CSE101 C Programming


Block Variables
• You can also declare variables that exist only
within the body of a compound statement (a
block):
{
int f;


}

©LPU CSE101 C Programming


Example-block scoped variable
#include<stdio.h>
int main()
{
int b=2;
{
int a=1; // a is block variable
printf("\nValue of a is:%d",a);
}
printf("\nValue of b is:%d",b);
return 0;
}

©LPU CSE101 C Programming


Global variables
• You can declare variables outside of any
function definition – these variables are
global variables.
• Any function can access/change global
variables.

©LPU CSE101 C Programming


Example-global variable
#include<stdio.h>
int a=1;// a is a global variable
void print();
int main()
{
printf("\nValue of a is:%d",a);
print();
return 0;
}
void print()
{
printf("\nValue of a is:%d",a);
}

©LPU CSE101 C Programming


More examples-Scope rules
#include<stdio.h>
int a=10;// a is a global variable
Output:
void print(); Value of a is:1
int main()
{ Value of a is:10
int a=1; Note:
printf("\nValue of a is:%d",a);// It will
access local a When we have same named
print();
return 0;
local and global variables,
} priority is always given to local
void print() variable first, that is why in
{
printf("\nValue of a is:%d",a); //It will main() function value of local a is
access global a printed, whereas in function
}
definition, there is no local
variable so preference is given
to global version of a
©LPU CSE101 C Programming
More examples-Scope rules
#include<stdio.h> Output:
Value of a is:10
int a=10;// a is a global variable
Value of a is:10
void print(); Value of a is:20
int main()
{
printf("\nValue of a is:%d",a);
print();
printf("\nValue of a is:%d",a);// Change
done by print to global a is reflected here
return 0;
}
void print()
{
printf("\nValue of a is:%d",a);
a=20;
}

©LPU CSE101 C Programming


More examples-Scope rules
#include<stdio.h> Output:
int main() a:500
{ a:50
int a=5; a:5
{
int a=50;
{
int a=500;
printf("\na:%d",a);
}
printf("\na:%d",a);
}
printf("\na:%d",a);
return 0;
}

©LPU CSE101 C Programming


Q1
What will be the output of the
following C code?
#include <stdio.h>
int x; A. 0
void m();
int main() B. 4
{ C. Compile time error
m();
D. Runtime error
printf("%d", x);
return 0;
}
void m()
{
x = 4;
}

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include <stdio.h> A. 8 3
int x = 5;
void m(); B. 3 8
void n();
int main()
C. 8 5
{ D. 5 3
int x = 3;
m();
printf("%d", x);
return 0;
}
void m()
{
x = 8;
n();
}
void n()
{
printf("%d", x);
}
©LPU CSE101 C Programming
Q3
What will be the output of following
code?
#include <stdio.h> A. 1
int main()
{ B. 2
int x=1; C. 3
{
x=2; D. Compile time error
{
int x=3;
}
}
printf("%d",x);
return 0;
}

©LPU CSE101 C Programming


Q4
In case of a conflict between the names of a
local and global variable what happens?
A. The global variable is given a priority.
B. The local variable is given a priority.
C. Which one will get a priority depends upon
which one is defined first.
D. The compiler reports an error.

©LPU CSE101 C Programming


Q5
What will be the storage class of variable i in the code
written below?
#include<stdio.h>
int main()
{
int i = 10;
printf("%d",i);
return 0;
}
A. Automatic storage class
B. Extern storage class
C. Static storage class
D. Register storage class

©LPU CSE101 C Programming


Q6
What will be the behaviour of following code?
#include<stdio.h>
int main()
{
register int a;
printf("\nEnter value of a:");
scanf("%d",&a);
return 0;
}
A. Program will work normally
B. Compile time error
C. Runtime error
D. None of the above

©LPU CSE101 C Programming


Q7
#include<stdio.h> A. 10
int incr(int i)
{ B. 4
static int count = 0; C. 3
count = count + i;
return (count); D. 2
}
int main()
{
int i,j;
for (i = 0; i <=2; i++)
j = incr(i);
printf("%d",j);
return 0;
}

©LPU CSE101 C Programming


Q8
#include<stdio.h> A. 2,2
void update();
int main() 2,3
{ B. 2,2
update();
update(); 2,2
return 0; C. 1,1
}
void update() 1,2
{ D. 2,1
auto int a=1;
static int b=1; 2,2
a++;
b++;
printf("%d,%d\n",a,b);
}

©LPU CSE101 C Programming


Q9
#include<stdio.h>
int main()
{
extern int a;
printf("%d",++a);
return 0;
}
int a;

A. 0
B. 1
C. -1
D. Compile time error

©LPU CSE101 C Programming


CSE101-Lec 10 and 11
User defined functions(Introduction to
Functions)
Parameter Passing mechanisms(Call by value
and Call by reference)

©LPU CSE101 C Programming


Functions

©LPU CSE101 C Programming


Divide and Conquer
• Best way to solve a problem is by dividing the
problem and solving it.
• Divide and conquer
– Construct a program from smaller pieces or
components
• These smaller pieces are called modules
– Each module more manageable than the original
program

©LPU CSE101 C Programming


Program Modules in C
Hierarchical boss function/worker function relationship.

©LPU CSE101 C Programming


Program Modules in C
• Functions
– Modules in C are called functions.
– Two categories of functions: Pre-defined(or library
functions) and User defined
– Programs combine user-defined functions with library
functions
• C standard library has a wide variety of functions for
performing common mathematical calculations, string
manipulations, character manipulations, input/output and
many more.
• C standard library makes your job easier.
• Functions like printf(), scanf(), pow() are standard library
functions.
• We can also write functions to define some specific task in a
program and these functions are called user-defined
functions.

©LPU CSE101 C Programming


What are functions??
• Functions
• A function is a set of statements that take inputs, do some
specific computation and produces output.
• The idea is to put some commonly or repeatedly done task
together and make a function so that instead of writing the
same code again and again for different inputs, we can call
the function.

©LPU CSE101 C Programming


Benefits of functions
• Functions help us in reducing code redundancy. If functionality
is performed at multiple places in software, then rather than
writing the same code, again and again, we create a function
and call it everywhere. This also helps in maintenance as we
have to change at one place if we make future changes to the
functionality.
• Functions make code modular. Consider a big file having many
lines of codes. It becomes really simple to read and use the
code if the code is divided into functions.
• Functions provide abstraction. For example, we can use
library functions without worrying about their internal
working.

©LPU CSE101 C Programming


Three important parts/ or components of any user
defined function

• Function declaration/ or Function prototype/


or Function signature
• Function definition
• Function calling

©LPU CSE101 C Programming


Function declaration/ or Function prototype/ or
Function signature

• A function declaration tells the compiler about the number of parameters


function takes, data-types of parameters and return type of function.
Putting parameter names in function declaration is optional in the
function declaration, but it is necessary to put them in the definition.
Below are an example of function declarations. (parameter names are not
there in below declarations)
Syntax:
return_type function_name( parameter list/or arguments );
Example 1:
int example(int,int);// Here function is returning integer value and accepting
two integer arguments
Example 2:
void example();// Here function is returning nothing and it is accepting no
argument

©LPU CSE101 C Programming


Function definition
• Function definition consists of the set of
statements that are required to be executed
when the function is used.
• It consists of body of the function along with
function header
• Function header is same as function
declaration but there is no semicolon after it
• Function header is followed by function body
where actual functionality of the function is
placed
©LPU CSE101 C Programming
Function definition-Example
Syntax:
return_type function_name( parameter list ) //Function Header
{
//body of the function // Function body
}
Example:
int sum(int x,int y) // sum is a user defined function which takes two integer parameters
{
int z;
z=x+y;
return z; //After adding two integers it is returning the result
}

©LPU CSE101 C Programming


Function Calling
• Once the function is declared and defined, we wish to use it.
So, for using the function we need to call it
• When the function is called in the main() function/ or some
other function, the control is transferred to the called
function, once the function definition is executed completely,
the control will come back to the main()/ or the other
function in which the calling statement has been placed, and
the execution will resume from the same point where it was
halted.
• Syntax of function calling:
function_name(<List_of_argument_values>);
Example: function(2,3);

©LPU CSE101 C Programming


Points to remember during function calling

• Function name and the number and type of arguments in the function call must
be same as that given in the function declaration and function header of the
function definition
• Names (and not the types) of variables in function declaration, function call and
header of function definition may vary
• Arguments may be passed in the form of expressions to the called function. In
such a case, arguments are first evaluated and converted to the type of formal
parameter and then the body of the function gets executed.
• If the return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, …);

©LPU CSE101 C Programming


Program example of function
#include<stdio.h> // FUNCTION DEFNITION
int sum(int a, int b);// FUNCTION DECLARATION int sum ( int a, int b)// FUNCTION HEADER
int main() {
{ // FUNCTION BODY
int num1, num2, total = 0; return (a + b);
printf(“\n Enter the first number : “); }
scanf(“%d”, &num1);
printf(“\n Enter the second number : “);
scanf(“%d”, &num2);
total = sum(num1, num2); //
FUNCTION CALL
printf(“\n Total = %d”, total);
return 0;
}

©LPU CSE101 C Programming


return statement in functions
• The return statement is used to terminate the execution of a function and return control to
the calling function. When the return statement is encountered, the program execution
resumes in the calling function at the point immediately following the function call.
• Calling function is one in which the function is called(usually main()), and the called function
is one whose definition is placed outside main() or/ some other function
• A return statement returns a value to the calling function. The syntax of return statement
can be given as
return <expression> ;
• Here expression is placed in between angular brackets because specifying an expression is
optional. The value of expression, if present, is returned to the calling function. However, in
case expression is omitted, the return value of the function is undefined.
• Programmer may or may not place the expression within parentheses.
• For functions that has no return statement, the control automatically returns to the calling
function after the last statement of the called function is executed.

©LPU CSE101 C Programming


Types of user defined functions
1) Function with no argument and no return value :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. (input, output statements and
actual logic ,all will be placed in the function definition)
2) Function with arguments but no return value : When a function has
arguments, it receive data from the calling function but it returns no
values.(input will be taken in the calling function, whereas output
statement and logic will be placed in the function definition)
3) Function with no arguments but returns a value : There could be
occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. (input statement
and logic will be placed in function definition and output statement will
be placed in calling function)
4) Function with arguments and return value: This kind of function returns
a value as well as it can accept arguments also.(input and output
statements will be placed in calling function and logic will be placed in
function definition)
©LPU CSE101 C Programming
Program example: Function with no argument and no return value
Write a program to add two numbers using function with no argument and
no return value
#include<stdio.h>
void add(); //Function declaration • Here input, output
int main() statements and logic all are
{
placed in the function
add(); //Function calling
return 0; definition
}
//Function definition
void add()
{
int a,b,sum;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("\n Sum of two numbers is:%d",sum);
}

©LPU CSE101 C Programming


Program example: Function with arguments but no return value
Write a program to add two numbers using function with argument but no
return value
#include<stdio.h> • Here input is taken in calling
void add(int,int); //Function declaration
function(i.e. main())
int main()
{ whereas output statement
int a,b; and logic is placed in the
printf("\n Enter two numbers:"); function definition
scanf("%d%d",&a,&b);
add(a,b); //Function calling //a, b are actual arguments • Note: Arguments in
return 0; function call statements are
}
actual arguments, whereas
//Function definition
void add(int x,int y) //x and y are formal arguments arguments in function
{ definition are formal
int sum; arguments
sum=x+y;
printf("\n Sum of two numbers is:%d",sum);
}

©LPU CSE101 C Programming


Program example: Function with no arguments but returns a value
Write a program to add two numbers using function no arguments but return
a value
#include<stdio.h>
int add(); //Function declaration • Here input statement
int main()
{
and logic is placed in
int result; the function definition
result=add(); //Function calling
printf("\n Sum is:%d",result); and then it returns sum,
return 0;
}
and output statement is
//Function definition written in the calling
int add()
{ function(i.e. main())
int a,b,sum;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a+b;
return sum;
}

©LPU CSE101 C Programming


Program example: Function with arguments and return value
Write a program to add two numbers using function with arguments and
return a value
#include<stdio.h>
int add(int,int); //Function declaration • Here input and output
int main()
{
statements are placed
int a,b,result; in the calling function
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b); (i.e. main()) and logic is
placed in the function
result=add(a,b); //Function calling //a, b are actual arguments
printf("\n Sum is:%d",result);
return 0; definition
}
//Function definition • Note: Arguments in
int add(int x,int y) //x and y are formal arguments
{ function call statements
int sum;
sum=x+y;
are actual arguments,
return sum; whereas arguments in
}
function definition are
formal arguments
©LPU CSE101 C Programming
Parameter Passing mechanisms in C/ or Argument Passing
techniques in C/ or Calling mechanisms in C

There are two ways in which arguments or parameters can be


passed to the called function.
• Call by value in which values of the variables are passed by the
calling function to the called function.
• Call by reference in which address of the variables are passed
by the calling function to the called function

©LPU CSE101 C Programming


Call by value
• In the Call by Value method, the called function creates new variables to store the value of the arguments
passed to it. Therefore, the called function uses a copy of the actual arguments to perform its intended
task.
• If the called function is supposed to modify the value of the parameters passed to it, then the change will
be reflected only in the called function. In the calling function no change will be made to the value of the
variables.
#include<stdio.h>
void add( int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2

©LPU CSE101 C Programming


Advantages and Disadvantages of Call by value

Advantages:
• The method doesn't change the original variable, so it is preserving data.
• Whenever a function is called it, never affect the actual contents of the
actual arguments.
• The other advantage could be arguments can be variables(e.g. x),
literals(e.g. 6,0…), or expressions(e.g. x+1)
Disadvantages:
• Copy of the variable is created hence it can consume additional storage
space
• Along with more space, it can take a lot of time to copy, thereby resulting in
performance penalty, especially if the function is called many times

©LPU CSE101 C Programming


Call by reference
• When the calling function passes arguments to the called function using call by
value method, the only way to return the modified value of the argument to the
caller is explicitly using the return statement. The better option when a function
can modify the value of the argument is to pass arguments using call by reference
technique.
• In call by reference, we declare the function parameters as pointers rather than
normal variables. When this is done, any changes made by the function to the
arguments ,are visible to the calling program.
• To indicate that an argument is passed using call by reference, address of the
variable is passed as an actual argument during function calling, and pointers will
act as formal arguments in the function definition to which the addresses will be
assigned

©LPU CSE101 C Programming


Call by reference(Program example)
#include<stdio.h>
void add( int *n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add( int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12

©LPU CSE101 C Programming


Advantages and Disadvantages of Call by reference

Advantages:
• It provides greater time and space efficiency as duplicate copies of the
arguments are not created
• In this method, there is no copy of the argument made. Therefore it is
processed very fast.
Disadvantages:
• Original values are not safe, as they can be modified
• We can only pass addresses as actual arguments(we cannot pass:
literals(1,2,3…) / or expressions(x+1,y+2..) as actual arguments

©LPU CSE101 C Programming


Call by value vs Call by reference
Parameters Call by value Call by reference

While calling a function, in


programming language instead of
While calling a function, when you
copying the values of variables,
Definition pass values by copying variables, it
the address of the variables is
is known as "Call By Values."
used it is known as "Call By
References.

In this method, a copy of the In this method, address of the


Arguments
variable is passed. variable is passed.

Changes made in a copy of Change in the variable also affects


Effect variable never modify the value of the value of the variable outside
variable outside the function. the function.

Allows you to make changes in the


Does not allow you to make any
Alteration of value values of variables by using
changes in the actual variables.
function calls.

Values of variables are passed Pointer variables are required to


Passing of variable
using a straightforward method. store the address of variables.

Value modification Original value not modified. The original value is modified.

©LPU CSE101 C Programming


Q1
Which of the following is a correct format for
declaration of function?
A. return-type function-name(argument type);
B. return-type function-name(argument type){}
C. return-type (argument type)function-name;
D. all of the mentioned

©LPU CSE101 C Programming


Q2
Which function definition will run correctly?
a) int sum(int a, int b)
return (a + b);
b) int sum(int a, int b)
{return (a + b);}
c) int sum(a, b)
return (a + b);
d) none of the mentioned

©LPU CSE101 C Programming


Q3
Which of the following is a valid function
declaration statement?
A.function1(int,int);
B.void function1(a,b);
C.void 1function(int,int);
D.void function1(int,int);

©LPU CSE101 C Programming


Q4
Which of the following is a valid function call
statement for user defined function: abc
a) abc(int);
b) void abc();
c) abc();
d) int abc(int);

©LPU CSE101 C Programming


Q5
What will be the output of the A. hi
following C code?
B. Run time error
#include <stdio.h>
void m()
C. Nothing will be displayed
{ D. Compile time error
printf("hi");
}
int main()
{
m();
return 0;
}

©LPU CSE101 C Programming


Q6
What will be the output of the
following C code? A. Compile time error
#include <stdio.h> B. hi
void m();
C. Infinite hi
int main()
{ D. Nothing
m();
return 0;
}
void m()
{
printf("hi");
m();
}

©LPU CSE101 C Programming

You might also like