C Programming Functions Explained
C Programming Functions Explained
UNIT – 5
FUNCTIONS
1. Pre-Defined Functions: All standard library functions – such as puts(), gets(), printf(),
scanf() etc.. These are the functions which already have a definition in header files (.h files
like stdio.h), so we just call them whenever there is a need to use them. main() is also built-
in function (predefined function).
2. User Defined Functions: A function is a block of code that performs a specific task. C
allows you to define functions according to your need. These functions are known as user-
defined functions.
Ex: check(), add() etc.......
2. User Defined Functions:
In order to make user defined functions need to establish 3 elements:
Function declaration
Function definition
Function call
2.1 Function Declaration: A function declaration tells the compiler about a function's name,
return type, and parameters.
Syntax: return_type function_name( parameter list );
This is also called as prototype. This must be end with a semicolon (;). should declare the
function as global declaration.
Examples:
i. int max(int num1, int num2); float(int a, in b);
ii. int max(int, int); // Parameter names are not important in function declaration only
1
UNIT – V COMPUTER PROGRAMMING
2.2 Function Definition: A function definition provides the actual body of the function. It
contains 6 elements:
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: The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
Local variable declaration: if any extra variables are needed in the function definition those
are declared as local to the function.
Function Body: The function body contains a collection of statements that define what the
function does.
Return value: returns obtained result to the function where it will be called.
Examples: i. return (p); //returns p variable result
ii. return (x*y); //returns expression value
iii. return (0); //returns direct value
The first 3 elements are called " function header" and last 3 elements are called " function
body".
Syntax: return_type function_name( parameter list )
{
body of the function
}
2.3 Function call: While creating a C function, you give a definition of what the function has to
do. Inorder to execute a declared function will have to call that function to perform particular task.
When a program calls a function, program control is transferred to the called function. 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 program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
Examples: i. mul(10,5); //pass direct values
ii. mul(m,5); //pass one direct value and one variable value
iii. mul(m,n); // pass both variable values
iv. mul(m+5,10); //pass expression, value
v. mul(10,mul(m,n)) //pass direct value, function return value
2
UNIT – V COMPUTER PROGRAMMING
2.4 Function Arguments: Calling programs pass parameters to called functions is known as
"actual arguments". The called functions access the information from calling function using
"formal arguments".
While calling a function, there are two ways that arguments can be passed to a function:
3
UNIT – V COMPUTER PROGRAMMING
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
3. Categories of functions: For better understanding of arguments and return value from the
function, user-defined functions can be categorized into 4 types:
Function with no arguments and no return value.
Function with no arguments and a return value.
Function with arguments and no return value.
Function with arguments and a return value.
4
UNIT – V COMPUTER PROGRAMMING
3.1 Function with no arguments and no return value: when a function has no arguments, it
doesn’t receive any data from the calling function. Similarly, when it doesn’t return a value, the
calling function doesn’t receive any data from the called function. There is no data transfer
between the calling function and called function. This explained using bellow picture:
5
UNIT – V COMPUTER PROGRAMMING
void prime(void)
{
int n,i,flag=0;
printf("Enter value:"); Output: Enter n value 5
scanf("%d",&n); prime number
for(i=1; i <= n; i++)
{
if(n%i==0)
{
flag++;
}
}
return (flag);
}
3.3 Function with arguments and no return value: when a function has arguments, it receives
data from the calling function. When it doesn’t return a value, the calling function doesn’t receive
any data from the called function. This explained using bellow picture:
6
UNIT – V COMPUTER PROGRAMMING
7
UNIT – V COMPUTER PROGRAMMING
}
int prime(int n)
{ Output: a prime number
int i,flag=0;
for(i=1; i <= n; i++)
{
if(n%i==0)
{
flag++;
}
}
return (flag);
}
4. Nested Functions: c permits nesting of functions freely. Main can call function1,
which calls function2, which calls funtion3, and soon. There is no limit to write nested
function in a program.
8
UNIT – V COMPUTER PROGRAMMING
}
float average(float d)
{
float ave;
ave=d/3;
return ave;
}
Output: the average of 3 numbers is 2.00000
Example 2: write a c program to calculate factorial of a given number using recursion function.
#include<stdio.h>
int factorial(int n);
main()
{
int fact,n=5;
fact=factorial(n);
printf(“the factorial of a given number is %d”,fact);
}
int factorial(int n)
{ Output: the factorial of a given number is 120
int fact;
if(n==1)
return (1);
else
fact=n*factorial(n-1);
return (fact);
}
Example 3: write a c program to calculate GCD of two number using recursion function.
#include<stdio.h>
int gcd(int n1, int n2);
main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1,n2));
9
UNIT – V COMPUTER PROGRAMMING
}
int gcd(int n1, int n2)
{
int rem;
rem=n1%n2; Output:
if (rem== 0) Enter two positive integers: 366 60
return n2; G.C.D of 366 and 60 is 6
else
return gcd(n2, rem);
}
6. Scope of a variable:
A scope is a region of the program, and the scope of variables refers to the area of the
program where the variables can be accessed after its declaration.
A scope of a variable means visibility and accessibility of a variable or a constant at
different point in program.
in C there are three types of scopes:
1. Block Scope
2. Function scope
3. Program Scope
1. Block Scope:
A Block is a set of statements enclosed within left and right braces ( { and } respectively).
Blocks may be nested in C (a block may contain other blocks inside it).
A variable declared in a block is accessible in the block and all inner blocks of that block,
but not accessible outside the block.
Example1:
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains declaration of x and y, so following statement is valid and
//prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible in this block
int y = 40;
x++; // Changes the outer block variable x to 11 y+
+; // Changes this block's variable y to 41 printf("x
= %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
10
UNIT – V COMPUTER PROGRAMMING
}
return 0;
}
Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
Example2:
#include<stdio.h>
void message();
void main()
{
int num1 = 0 ; // Local to main
printf("num1=%d\n",num1);
message();
}
void message()
{
int num1 = 1 ;
// Local to Function message
printf("num1=%d\n",num1);
}
Output:
num1=0
num2=1
Explanation:
1. In both the functions main() and message() we have declared same variable. Since these
two functions are having different block/local scope, compiler will not throw compile
error.
2. Whenever our control is in main() function we have access to variable from main()
function only. Thus 0 will be printed inside main() function.
3. As soon as control goes inside message() function , Local copy of main is no longer
accessible. Since we have re-declared same variable inside message() function, we can
access variable local to message(). “1” will be printed on the screen
Example3:
void main()
{
{
int a=5; printf(“a=
%d\n”,a);
}
{
int a= 10;
a=a+1;
printf(“a=%d\n”,a);
11
UNIT – V COMPUTER PROGRAMMING
}
}
OUTPUT:
a= 5
a=10
[Link] scope: A variable can be accessed within the function then it is said to be function
scope.
Example1:
void main()
{
int a=12;
{ OUTPUT:
int a=5; a= 5
printf(“a=%d\n”,a); a=13
}
a=a+1; printf(“a=
%d\n”,a);
}
In the above program int a =12 is having a function scope. The variable is accessed until the
function execution completed. .
Example2:
int main()
{
int x = 1, y = 2, z = 3;
printf(" x = %d, y = %d, z = %d \n", x, y, z); OUTPUT:
{ x=1,y=2,z=3
int x = 10; x=10,y=20.0,z=3
float y = 20; x=10,y=20.0,z=100
printf(" x = %d, y = %f, z = %d \n", x, y, z);
{
int z = 100;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
}
}
}
In the above code x=1,y=2,z=3 having functions scope these variables can access
throughout the function.
x=10,y=20,z=100 having block scope. These variables can access with in respective
blocks.
7. Storage classes:
In C language, each variable has a storage class which decides the following things:
Scope i.e in which all functions, the value of the variable would be available.
Default initial value i.e if we do not explicitly initialize that variable, what will be its
default initial value.
12
UNIT – V COMPUTER PROGRAMMING
Lifetime of that variable i.e for how long wills that variable exist.
The following storage classes are mostly used in C programming:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
1. Automatic (Auto) Storage Class:
A variable declared inside a function without any storage class specification, is by default
an automatic variable.
They are created when a function is called and are destroyed automatically when the
function exits. Automatic variables can also be called local variables because they are local
to a function. By default they are assigned garbage value by the compiler.
1. This is default storage class
2. All variables declared are of type Auto by default
3. In order to Explicit declaration of variable use ‘auto’ keyword
Ex: auto int num1; //Explicit declaration
int num1; //implicit declaration
Features:
Storage Memory (RAM)
Example:
void main() Output:
{ num=10
auto int num=20; num=20
{
int num=10; //by default automatic storage class
printf(“num=%d\n”,num);
}
printf(“num=%d\n”,num);
}
In the above program the two variables are declared in different blocks, so they are treated
as different variables.
13
UNIT – V COMPUTER PROGRAMMING
2. Global Variables are declared outside the function and are accessible to all functions in the
program
3. Generally , External variables are declared again in the function using keyword extern
4. In order to Explicit declaration of variable use ‘extern’ keyword
Features:
Storage Memory (RAM)
Scope Global
Example1:
The extern keyword is used before a variable to inform the compiler that this variable is
declared somewhere else. The extern declaration does not allocate storage for variables.
Example:
int num = 75 ;
void display();
void main() Output :
{ Num : 75
extern int num ; Num : 75
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
Note:
1. Declaration within the function indicates that the function uses external variable
14
UNIT – V COMPUTER PROGRAMMING
2. Functions belonging to same source code , does not require declaration (no need to write
extern)
3. If variable is defined outside the source code , then declaration using extern keyword is
required
3. Static Storage Class: A static variable tells the compiler to persist the variable until the end of
program. Static is initialized only once and remains into existence till the end of program. Static
variable value is not-reinitialized when a same function called again and again.
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
Example:
void test(); //Function declaration (discussed in next topic)
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
Output :
1 2 3
4. Register Storage Class: Register variable inform the compiler to store the variable in CPU
register instead of memory. Register variable has faster access than normal variable.
Scope: Local to the function in which it is declared. We can never get the address of such
variables. Syntax: register int number;
Scope: Local to the block.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of method block, where the variable is defined, doesn't finish its
execution.
Even though we have declared the storage class of variable number as register, we cannot
surely say that the value of the variable would be stored in a register. This is because the number
of registers in a CPU is limited. Also, CPU registers are meant to do a lot of important work.
Thus, sometimes it may not be free. In such scenario, the variable works as if its storage class is
auto.
Example:
#include <stdio.h>
main()
{
15
UNIT-V COMPUTER PROGRAMMING
DATA FILES:
A file in general is a collection of related records stored on a secondary storage device like hard disk.
Example: files are student information, marks obtained in an exam, employee salaries, etc. Each record is a
collection of related items called fields, such as “student name”, “date of birth”, “subjects registered”, etc.
The common operations associated with a file are:
• Read from a file (input)
• Write to a file (output)
• Append to a file (write to the end of a file)
• Update a file (modifying any location within the file)
TYPES OF FILES: In
1) ASCII Text files: A text file is a stream of characters that can be sequentially processed by a computer in
forward direction. For this reason a text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time. Because text files only process characters, they can only read or
write data one character at a time.
In a text file, each line contains zero or more characters and ends with one or more characters that specify the
end of line. Each line in a text file can have maximum of 255 characters. A line in a text file is not a c string,
so it is not terminated by a null character.
Example: an int value will be represented as 2 or 4 bytes of memory internally but externally the int value
will be represented as a string of characters representing its decimal or hexadecimal value.
2) Binary files A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes. Like a text file, a binary file is a collection of bytes. In C Language a byte
and a character are equivalent.
Therefore, a binary file is also referred to as a character stream with following two essential differences.
• A binary file does not require any special processing of the data and each byte of data is transferred
to or from the disk unprocessed.
• C places no constructs on the file, and it may be read from, or written to, in any manner the
programmer wants.
Operations on files:
1. Naming a file: set own name to identify files in a disc and with extension (.).
Ex: simple.c, [Link]
2. Opening and closing a file
3. Reading and writing a file
Accessing a file: Accessing a file is a four step process:
• Declaring a file pointer variable
• Opening a connection to a file
• Reading/writing data from/to the file
• Closing the connection
UNIT-V COMPUTER PROGRAMMING
• Declaring a file pointer variable: In a disk we may have number of files. In order to access a particular file,
we must specify the name of the file that has to be used. We use a file pointer variable that points to a
structure FILE which is defined in stdio.h. The general syntax for declaring a file pointer is:
Syntax: FILE *file_pointer_name;
Opening a Connection to a File: In order to use a file on a disk you must establish a connection with it. A
connection can be established using the fopen function. The function takes the general form:
Syntax: FILE *fopen(const char *file_name, const char *mode);
The file_name is the name of the file to be accessed and it may also include the path. The access_mode
defines whether the file is open for reading, writing or appending data.
Different file modes are used in opening a file:
File access modes
Access mode Description
“w” Open a file for writing only. If the file does not exist create a new one. If the file exists it will be
overwritten.
“a” Open a file for appending only. If the file does not exist create a new one.
New data will be added to the end of the file. “r+” Open an existing file for reading and writing “w+”
Open a new file for reading and writing
“a+” Open a file for reading and appending. If the file does not exist create a new one.
Example: FILE *fp;
fp = fopen("my [Link]", "a");
The function fopen returns a pointer to the file pointer, which is defined in the stdio.h headier file. If the file
is exist in hard disc the function successfully returns a pointer to the file. If an error is encountered while
establishing a connection the functions returns NULL.
Closing the Connection to a File: The function fclose is used to close the file. The function also flushes all
the buffers that are maintained for the file.
Syntax: fclose(FILE *fp)
When closing the file the file pointer “fp” is used as an argument of the function. When a file is successfully
closed the function fclose returns a zero and any other value indicates an error.
Reading Data from a File : C Provides four functions to read text files from hard disk.
a) fscanf() b) fgets() c) fgetc() d) fread() Unformatted I/O:
To read a character from I/O using fgetc() function.
Syntax: fgetc(FILE *fp) ;
16
UNIT-V COMPUTER PROGRAMMING
Formatted I/O:
To read alpha-numeric data from I/O using fscanf() function.
Syntax: fscanf( FILE *stream, const char
*format,…);
Example: fscanf(fp,%s%d”,name,&rno);
To read one block of data from a file at a time.
Syntax is: fread(void *str, size_t size, size_t num, FILE *stream); Here str is a pointer to an array in which
the data is stored.
size indicates the size of each array element.
num specifies the number of elements to read.
stream is a file pointer that is associated with the opened file for reading.
size_t is an integral type defined in the header file stdio.h.
Writing Data to a File: C Provides four functions to read text files from hard disk.
b) fprintf() b) fputs() c) fputc() d) fwrite() Unformatted I/O:
To read a character from I/O using fputc() function.
Syntax: fputs(string, file_pointer)
To read a string from I/O using fputs() function.
Syntax: fputs(string, file_pointer) Example: fputs(message,fp);
Formatted I/O:
To read alpha-numeric data from I/O using fprintf() function.
Syntax: fprintf(file_pointer, “%s”, string)
Example: fprintf(fp,"%s",message);
For writing a record of fixed length C Language provides fwrite function. The
Syntax: fwrite(structure variable, sizeof (record),1,fp)
Here sturucture varialble: is the name of the variable sizeof(record): gives the record length to write
‘1’ indicates that you wish to write one record at a time fp: is the file pointer.
17
UNIT-V COMPUTER PROGRAMMING
18
UNIT-V COMPUTER PROGRAMMING
printf("\nError while opening file");
}
Output:
opening the [Link] and [Link] copying the content for source to dest COMPLETED
3. write a program to count no of characters, lines in a file named "[Link]" #include<stdio.h>
void main()
{
FILE *fp;
int ccount=0,lcount=0; char ch;
printf(“opening the [Link] file\n”); fp=fopen("[Link]","r"); // file to read if(fp != NULL ) //if success
{
while(!feof(fp))
{
ch=fgetc(fp); ccount++;
if(ch=='\n') lcount++;
}
}
printf("The File [Link] contains %d Characters\n It contains %d lines",ccount,lcount); fcloseall();
else
printf("\nError while opening file");
}
Output:
opening the [Link] file
The File [Link] contains 82 Characters It contains 2 lines
4. Write a c program to merge two files in to third file. The name of files should be entered using command
line arguments.
#include<stdio.h> void main ( )
fp1=fopen("[Link]","r");
fp2=fopen("[Link]","r");
fp3=fopen("[Link]","w");
while( ( c=f g e t c ( fp1 ) )!=EOF) f p u t c ( c , fp3 ) ;
while ( ( c=f g e t c ( fp2 ) )!=EOF) f p u t c ( c , fp3 ) ;
19
UNIT-V COMPUTER PROGRAMMING
p r i n t f ( ”merged file1&file2 in t o f i l e 3 ” ) ; f c l o s e ( fp1 ) ;
f c l o s e ( fp2 ) ; f c l o s e ( fp3 ) ;
}
Random access to files: Until now we read and write data to a file sequentially. In some situations
we need only a particular part of file and not other parts. This can be done with the help of fseek, ftell,
rewind functions.
ftell: ftell ( ) returns the current position of cursor in the file. It takes a file pointer and returns
number of type long, that corresponds to the current position. This is useful in saving the current
position of file.
Example: n=ftell(fp); //n’ would give the relative offset (in bytes) of current position. i.e., n
bytes have all ready been read/ write.
rewind: It takes file pointer and resets the cursor position to the start of the file.
Example: rewind(fp);
fseek: This function is used to move file position to a desired location within file. Syntax: fseek (file
pointer, offset, position)
file pointer is pointer to the file in which random read or write operations are to be
performed.
Offset is the position at which the cursor is placed so that read or write operations will be
performed at this position
Offset Positive ─ move forward Negative ─move backward
example: if the offset value is set to 10 then next read or write operation will be performed from 10th position
of the file.
Position can acquire any of the following values
0 ─ indicates offset value is to taken from the beginning of the file
1─ indicates offset value is to taken from the current position of the file 2─ indicates offset value is to taken
from the end of file
Example: fseek (Fp1, 0L, 0); → go to the beginning
fseek(fp1,m,1) → go forward by m bytes from current file position.
If the fseek file operation is successful, it returns 0 else returns -1 (error occur)
Program1: Write a c program to store roll number (2 bytes), name (20 bytes) and marks(2 bytes) of the
students randomly in a file. Use roll number of the student to indicate the location of the record written in the
file. For example roll no. 4 means the record will be stored at 4th position in the file. #include <stdio.h>
struct record
{
int roll;
20
UNIT-V COMPUTER PROGRAMMING
char name[20]; int marks;
}student; int main()
{
int flag=1,pos; FILE *fp; char c;
fp = fopen("[Link]", "w");
if(fp != NULL) //if not the end of file
{
while(flag==1)
{
printf("\n enter roll number of student ");
scanf("%d",&[Link]);
if([Link]==0)
break;
printf("enter name of student:\t");
scanf("%s",&[Link]);
printf("enter marks:\t");
scanf("%d",&[Link]);
pos=([Link]-1)*sizeof(student);
printf("pos value is:\t %d",pos);
fseek(fp,pos,0);
fwrite(&student,sizeof(student),1,fp);
}
fclose(fp); //close the file
}
else
{ printf("\nError while opening file...");
}
getch();
return 0;
}
Out put:
enter roll number of student: 1
enter name of student: murthy enter marks: 99
pos value is: 0
enter roll number of student: 2 enter name of student: rao enter marks: 98
21
UNIT-V COMPUTER PROGRAMMING
pos value is: 24
enter roll number of student: 4 enter name of student: raj enter marks: 97
pos value is: 72
enter roll number of student: 0
Program2: Write a program to input [Link] file with n numbers. Copy even numbers in [Link] file
and odd numbers to [Link] file from DATA file.
#include<stdio.h> int main(void)
{
int n,i,j,k;
FILE *a,*b,*c;
a=fopen("[Link]","w");
printf("Enter the number of values u want to enter :\t "); scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter %d value:\t",i); scanf("%d",&j);
putw(j,a);
}
fclose(a); a=fopen("[Link]","r");
b=fopen("[Link]","w");
c=fopen("[Link]","w");
while((k=getw(a))!=EOF)
{
if(k%2==0)
putw(k,b);
else
putw(k,c);
}
fclose(a); fclose(b); fclose(c);
b=fopen("even","r");
c=fopen("odd","r");
printf("\nCONTENTS OF EVEN FILE ARE: ");
while((k=getw(b))!=EOF)
{
printf("%d ",k);
}
22
UNIT-V COMPUTER PROGRAMMING
printf("\nCONTENTS OF ODD FILE ARE: ");
while((k=getw(c))!=EOF)
{
printf("%d ",k);
}
fclose(b); fclose(c); getch(); return 0;
}
Output:
Enter the number of values u want to enter: 5 enter 1 value: 1
enter 2 value: 2
enter 3 value: 3
enter 4 value: 4
enter 5 value: 5
Call by reference:
#include <stdio.h>
Before swapping:
x = 10, y = 20
void swap(int *a, int *b);
After swapping:
void main() x = 20, y = 10
{
int x = 10, y = 20;
printf("Before swapping:\n");
printf("x = %d, y = %d\n", x, y);
printf("After swapping:\n");
printf("x = %d, y = %d\n", x, y);
}
23
UNIT-V COMPUTER PROGRAMMING
Call by value;
#include <stdio.h>
void main()
{
int x = 10, y = 20;
printf("Before swapping:\n");
printf("x = %d, y = %d\n", x, y);
void add(void);
void main()
24
{
add();
}
UNIT-V COMPUTER PROGRAMMING
void add(void)
{
int a = 10, b = 20, sum;
sum = a + b;
printf("Sum = %d", sum);
}
Output: 30
Explanation:
Values are fixed inside the function.
void main()
{
add(10, 20);
}
int add(void);
void main()
{
int result;
result = add();
25
printf("Sum = %d", result);
}
int add(void)
UNIT-V COMPUTER PROGRAMMING
{
int a = 10, b = 20;
return a + b;
}
Explanation:
Value is returned to the calling function.
void main()
{
int result;
result = add(10, 20);
printf("Sum = %d", result);
}
void main()
{
int arr[2] = {1, 2};
change(arr);
void main()
{
int arr[3] = {10, 20, 30};
update(arr);
#include <stdio.h>
struct student
{
int roll;
int marks;
};
void main()
{
UNIT-V COMPUTER PROGRAMMING
struct student st = {101, 65};
update(&st);
Recursion:
When a called function in turn calls another function a process of chaining occurs .
Recursion is a special case of this process, where a function calls itself.
main()
{
Printf(“This is an example of recursion:\n”);
main();
}
Output:
This is an example of recursion:
This is an example of recursion:
This is an example of recursion:
This is an example of recursion:
This is an example of recursion:
This is an example of recursion:
This is an example of recursion:
………
Example program:
#include <stdio.h>
void main()
{
int num, result;
result = fact(num);
28
printf("Factorial = %d", result);
}
UNIT-V COMPUTER PROGRAMMING
int fact(int n)
{
if (n == 0) // base case
return 1;
else
return n * fact(n - 1);
}
void fun() {
auto int a = 10;
printf("%d", a);
}
Output: 10
void fun() {
register int count = 0;
count++;
}
3. static Storage Class
void fun() {
static int x = 0;
x++;
printf("%d\n", x);
} 29
int main() {
fun();
fun();
UNIT-V COMPUTER PROGRAMMING
fun();
return 0;
}
Output:
1
2
3
4. extern Storage Class
File 1 (main.c)
int x = 10;
File 2 (test.c)
extern int x;
void fun() {
printf("%d", x);
}
int main() {
FILE *fp;
char ch;
//Each character from the file is read one by one until the end of the file is reached.
30
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
UNIT-V COMPUTER PROGRAMMING
fclose(fp);
return 0;
}
Output
Hello File Handling
Simple Explanation:
fopen("[Link]","w") → creates the file and writes data
fprintf() → writes text into the file
fopen("[Link]","r") → opens file for reading
fgetc() → reads one character at a time
printf() → prints the character on screen
fclose() → closes the file
until now we have been using scan and printf function to read and write data.
#include <stdio.h>
int main() {
FILE *fp;
char name[20], line[50];
int age;
31
/* Read remaining line using fgets */
fgets(line, 50, fp);
printf("Reading string data:\n");
printf("%s", line);
UNIT-V COMPUTER PROGRAMMING
fclose(fp);
return 0;
}
🔹 Output
Reading formatted data:
Name = Alice
Age = 21
Explanation:
File is created using fopen("[Link]","w").
32