0% found this document useful (0 votes)
8 views34 pages

C Programming Functions Explained

This document provides an overview of functions in C programming, detailing their usage, types, and structure. It explains the differences between predefined and user-defined functions, as well as how to declare, define, and call functions. Additionally, it covers function arguments, recursion, and variable scope within functions.

Uploaded by

u27769223
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views34 pages

C Programming Functions Explained

This document provides an overview of functions in C programming, detailing their usage, types, and structure. It explains the differences between predefined and user-defined functions, as well as how to declare, define, and call functions. Additionally, it covers function arguments, recursion, and variable scope within functions.

Uploaded by

u27769223
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT – V COMPUTER PROGRAMMING

UNIT – 5
FUNCTIONS

1. Functions: A function is a group of statements that together perform a task. Every C


program has at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.
1.1 Function Usage:
1. C functions are used to avoid rewriting same code again and again in a program.
2. The main usage of functions is dividing a big task into small pieces to improve
understand ability of very large c programs.
3. We can call functions any number of times in a program and from any place in a
program.
1.2 Functions are mainly divided into two types:

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

their type is required, so this is also valid declaration.


iii. mul(); //this is also valid sometime not to mention return type and parameters.
iv. void mul(void); //'void' means nothing to catch and nothing to pass.

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

Example: write a c program to find maximum of two numbers using functions


Program: /* function returning the max between two numbers */
#include <stdio.h>

2
UNIT – V COMPUTER PROGRAMMING

int max(int num1, int num2); /*global function declaration*/


main ()
{
int a = 100, b = 200, ret;
ret = max(a, b); /* function call to pass a, b values to called function*/
printf( "Max value is : %d\n", ret );
}
int max(int num1, int num2) /*function definition or called function*/
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Output: Max value is: 200

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:

Call Type Description


This method copies the actual value of an argument into the formal
Call by Value parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument
This method copies the address of an argument into the formal
Call by parameter. Inside the function, the address is used to access the
Reference actual argument used in the call. This means that changes made to
the parameter affect the argument.

Example: /* Call by Value*/


#include <stdio.h>
void change(int num);
main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(x); /*passing value to called function*/
printf("After function call x=%d \n", x);
}
void change(int num)
{
printf("Before adding value inside function num=%d \n",num);

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

Example: /*Call by Reference*/


#include <stdio.h>
void change(int *num);
main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(&x); //passing reference in function
printf("After function call x=%d \n", x);
}
void change(int *num)
{
printf("Before adding value inside function num=%d \n",*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=200

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:

Example: write a c program to print given number is prim or not


program: #include<stdio.h>
void prime(void);
main()
{
prime(); /*no argument is passed to called function */
}
void prime(void)
{
int n,i,flag=0;
printf("Enter value:");
scanf("%d",&n);
for(i=1; i <= n; i++) Output:
{ Enter n value 5
if(n%i==0) 5 is prime number
{
flag++;
}
}
if (flag>2)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.",n);
}
3.2 Function with no arguments and a return value: when a function has no arguments, it
doesn’t receive any data from the calling function. Similarly, when a function has returned a
value, the calling function receives data from the called function. This explained using bellow
picture:

5
UNIT – V COMPUTER PROGRAMMING

Example: write a c program to print given number is prim or not


program: #include<stdio.h>
int prime(void);
main()
{
int a;
a= prime();
if (a>2)
printf("not a prime number.");
else
printf(" prime number.");
}

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

Example: write a c program to print given number is prim or not


program: #include<stdio.h>
void prime(int n);
main()
{
int n=5;
prime(n);
}
void prime(int n)
{
int i,flag=0;
for(i=1; i <= n; i++)
{
if(n%i==0)
{
flag++; Output: a prime number
}
}
if (flag>2)
printf("not a prime number.");
else
printf(" a prime number.");
}
3.4 Function with arguments and a return value: when a function has arguments, it receives
data from the calling function. Similarly, when it has returned a value, the calling function
receives data from the called function. This explained using bellow picture:

Example: write a c program to print given number is prim or not


program: #include<stdio.h>
int prime(int n);
main()
{
int n=5,a;
a=prime(n);
if (a>2)
printf("not a prime number.");
else
printf(" a prime number.");

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.

Example: write a c program to print average of 3 numbers using nested functions


Program:
#include<stdio.h>
int sum(int a,int b, int c);
float average(float d);
main()
{
int a=1, b=2, c=3;
float e;
e=sum(a,b,c);
printf(“the average of 3 numbers is %f=”,e);
}
int sum(int a,int b, int c);
{
float d,avg;
d=a+b+c;
avg=average(d);
return avg;

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

5. Recursion Functions: When a function in turn calls itself is known as recursion.


Example1:
main()
{
printf(“hello “);
main(); //The main() function calls infinite times.
}
Output: hello hello hello hello (infinite times)

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)

Scope Local / Block Scope

Life time Exists as long as Control remains in the block

Default initial Value Garbage

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.

2. External (extern ) Storage Class:


One important thing to remember about global variable is that their values can be changed by any
function in the program.
1. Variables of this storage class are “Global 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

Life time  Exists as long as variable is running


 Retains value within the function

Default initial Value Zero

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

register int i=10; printf("value is %d \


n", i);
}
Output: value is 10

7.1 Which storage class should be used and when?


To improve the speed of execution of the program and to carefully use the memory space by the
variables, following points should be kept in mind while using storage classes:
 We should use static storage class only when we want the value of a variable to remain same every
time we call it using different function calls.
 We should use register storage class only for those variables that are often used in our program.
CPU registers are limited and thus should be used carefully.
 We should use external or global storage class only for those variables that are being used by almost
all the functions in the program.
 If we do not have the purpose of any of the above mentioned storage classes, then we should use the
automatic storage class. Most of the times, we use automatic storage class.
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

“r” Open an existing file for reading only.

“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) ;

 To read a string from I/O using fgets() function.


Syntax: char *fgets(char *string, int max_characters, FILE file_pointer)

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

Some of the important programs from previous papers


1) c program to display contents of a file #include<stdio.h>
void main()
{
FILE *fp;
char ch, file[100]; printf(“opening the file\n”);
fp = fopen(file, "r"); //open read-onlyopening the file if(fp != NULL) //if not the end of file
{
printf(“contents of file is\n”);
Ch = fgetc(fp); //read the 1st character while ( ch != EOF)
{
putchar(ch);
ch= fgetc(fp);//read next character
}
fclose(fp); ////close the file
}
else
printf("\nError while opening file...");
}
Output:
contents of file is Hello welcome

2. Write a c program which copies one file to another #include <stdio.h>


void main()
{
FILE *sp,*dp; char ch;
printf(“opening the [Link] and [Link]\n”); sp = fopen("./[Link]", "r");
dp = fopen("./[Link]", "w");
if(sp != NULL || dp != NULL ) //if success
{
printf("copying the content for source to dest"); while((ch=getc(sp))!= EOF)
{
putc(ch,dp);
}
printf("\nCOMPLETED"); fclose(sp);//close the file fclose(dp);
}
else

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 ( )

FILE ∗ fp1; FILE ∗ fp2; FILE ∗ fp3; char c ;


{

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

CONTENTS OF EVEN FILE ARE: 2 4 6 CONTENTS OF ODD FILE ARE: 3 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);

swap(&x, &y); // passing addresses

printf("After swapping:\n");
printf("x = %d, y = %d\n", x, y);
}

void swap(int *a, int *b)


{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

23
UNIT-V COMPUTER PROGRAMMING
Call by value;

#include <stdio.h>

void swap(int a, int b);

void main()
{
int x = 10, y = 20;

printf("Before swapping:\n");
printf("x = %d, y = %d\n", x, y);

swap(x, y); // passing values


Before swapping:
printf("After swapping:\n"); x = 10, y = 20
printf("x = %d, y = %d\n", x, y);
Inside swap function:
} a = 20, b = 10

void swap(int a, int b) After swapping:


{ x = 10, y = 20
int temp;
temp = a;
a = b;
b = temp;

printf("Inside swap function:\n");


printf("a = %d, b = %d\n", a, b);
}

Types of Functions based on Arguments & Return Type


There are 4 types

1️⃣ No Arguments & No Return Value


 Function does not take input
 Function does not return output
Program Example
#include <stdio.h>

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.

2️⃣ Arguments but No Return Value


 Function accepts input
 Function does not return value
Program Example
#include <stdio.h>

void add(int a, int b);

void main()
{
add(10, 20);
}

void add(int a, int b)


{
int sum;
sum = a + b;
printf("Sum = %d", sum);
}
Explanation:
Data is passed through arguments. 30

3️⃣ No Arguments but Returns a Value


 Function does not take input
 Function returns output
Program Example
#include <stdio.h>

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.

4️⃣ Arguments and Returns a Value (Most important)


 Function takes input
 Function returns output
Program Example
#include <stdio.h>

int add(int a, int b);

void main()
{
int result;
result = add(10, 20);
printf("Sum = %d", result);
}

int add(int a, int b)


{
return a + b;
}

Array as Parameter (Modify Array)


#include <stdio.h>

void change(int a[]);

void main()
{
int arr[2] = {1, 2};

change(arr);

printf("%d %d", arr[0], arr[1]);


}

void change(int a[])


{
a[0] = 5;
26
a[1] = 10;
}
Output
5 10
UNIT-V COMPUTER PROGRAMMING
#include <stdio.h>

void update(int a[])


{
a[1] = 50; // change only the 2nd element
}

void main()
{
int arr[3] = {10, 20, 30};

update(arr);

printf("%d %d %d", arr[0], arr[1], arr[2]);


}
Output: 10 50 30

1. int arr[3] = {10, 20, 30};


— An array with 3 values.
2. update(arr);
— We pass the array to the function. This gives the function access to the same array,
not a copy.
3. a[1] = 50;
— Inside the function, we change only one element (second element).
4. arr[0]
— This element is never changed → stays 10.
5. arr[1]
— This element is updated → becomes 50.
6. arr[2]
— This element is not touched → stays 30.

Example: Modify structure member using function (structure pointer)

#include <stdio.h>

struct student
{
int roll;
int marks;
};

void update(struct student *s)


{
s->marks = 80; 27
}

void main()
{
UNIT-V COMPUTER PROGRAMMING
struct student st = {101, 65};

update(&st);

printf("Roll = %d\n", [Link]);


printf("Marks = %d\n", [Link]);
}
Output:
Roll = 101
Marks = 80

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>

int fact(int n);

void main()
{
int num, result;

printf("Enter a number: ");


scanf("%d", &num);

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);
}

Storage Class Modifiers in C

Storage class specifiers define:


 Scope – where a variable can be used
 Lifetime – how long it exists in memory
 Storage location – where it is stored
 Default initial value

There are 4 main storage class specifiers in C:


1. auto
2. register
3. static
4. extern

1. auto Storage Class

void fun() {
auto int a = 10;
printf("%d", a);
}
Output: 10

2. register Storage Class

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);
}

Storage Class Scope Lifetime Default Value Memory


auto Local Within block Garbage Stack
register Local Within block Garbage CPU register
static Local/Global Entire program 0 Data segment
extern Global Entire program 0 Data segment

File Creation and Read (File Handling)


#include <stdio.h>

int main() {
FILE *fp;
char ch;

/* Create and write into file */


fp = fopen("[Link]", "w");
fprintf(fp, "Hello File Handling");
fclose(fp);

/* Read from file */


fp = fopen("[Link]", "r");

//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;

/* Create file and write data */


fp = fopen("[Link]", "w");
fprintf(fp, "Name: Alice\n");
fprintf(fp, "Age: 21\n");
fputs("This is File I/O example.\n", fp);
fclose(fp);

/* Open file for reading */


fp = fopen("[Link]", "r");

/* Read formatted data */


fscanf(fp, "Name: %s\n", name);
fscanf(fp, "Age: %d\n", &age);

printf("Reading formatted data:\n");


printf("Name = %s\n", name);
printf("Age = %d\n\n", 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

Reading string data:


This is File I/O example.

Explanation:
File is created using fopen("[Link]","w").

fprintf() writes formatted data (name and age).

fputs() writes a full string into the file.

File is closed to save data.

File is reopened in read mode (r).

fscanf() reads formatted data (name and age).

fgets() reads the remaining line from the file.

Data is printed on the console.

File is closed again.

32

You might also like