Unit V
Unit V
Unit V
3. Function Call:
➢ The function call tells the compiler when to execute the function definition. When a function call is executed,
the execution control jumps to the function definition where the actual code gets executed and returns to
the same functions call once the execution completes.
➢ The function call is performed inside the main function or any other function or inside the function itself.
Syntax
functionName(parameters);
Example:
add(15, 20);
Q 2. define parameter. What are its types.
➢ Parameters are the data values that are passed from calling function to called function.
➢ Parameters are also called as arguments.
➢ In C, there are two types of parameters and they are as follows...
o Actual Parameter
o Formal Parameters
➢ The actual parameters are the parameters that are specified in calling function.
➢ The formal parameters are the parameters that are declared at called function.
➢ When a function gets executed, the copy of actual parameter values are copied into formal parameters.
#include<stdio.h>
int addition(int,int) ; // function declaration
int main()
{
int num1, num2,
result ;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
return 0;
}
int addition(int a, int b) // function definition
{
return a + b ;
}
Output:
Enter any two integer numbers : 23 54
SUM = 77
In the above example addition() is user defined function.
Q 5. Explain different types of functions based on parameters and return values?
Based on parameters and return types, functions are classified into 4 types:
1. Function without parameters and without return values
2. Function with parameters and without return values
3. Function without parameters and with return values
4. Function with parameters and with return values
69
Example Program
#include<stdio.h>
void addition(int, int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
70
#include<stdio.h>
int addition() ; // function declaration
int main()
{
int result ;
result = addition() ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
4. Function with parameters and with return values:
These types of functions contain both parameters and return values.
Example Program
#include<stdio.h>
int main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
71
Example Program
#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Q 7 Explain the Pass arrays to a function in C
➢ In C programming, you can pass an entire array to functions.
➢ To pass array to a function, only the name of the array is passed to the function (similar to one-dimensional
arrays).
Example Program:
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
73
sum += num[i];
}
return sum;
}
Output:
Result = 162.50
Explanation:
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
However, notice the use of [] in the function definition.
float calculateSum(float num[])
{
... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.
Q 8. Explain Pass Multidimensional Arrays to a Function in C.
➢ To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to
one-dimensional arrays).
Example Program:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
74
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Explanation:
➢ Note the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
➢ This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with
more than 2 dimensions as a function argument.
➢ When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.
For example,
void displayNumbers(int num[][2])
{
// code
}
Q 9. Explain the Scope of Variables in C?
➢ The availability of a variable in a program or function is referred to as the scope of variable in C language.
➢ A variable, for example, may be accessed only within a single function/block of code (your apartment key) or
throughout the whole C program (the shared access key).
➢ We can associate the room keys with the local variables in C language because they only work in that single
room. The term global variables refers to variables (keys) that are accessible to the whole program
(apartment complex).
Q 10. Define local and global variables.
Local Variable:
➢ Local variable is declared inside a function.
➢ Local variables are created when the function has started execution and is lost when the function terminates.
➢ If a value of local variable is updated, it will effect within that function only.
Example:
#include <stdio.h>
int main()
{
int x = 30;
75
Q 12. Define storage class. What are the storage classes in C. Explain with example?
➢ Storage classes are used to define storage location (whether RAM or Register), scope, lifetime and the default
value of a variable.
➢ In C language, there are FOUR storage classes and they are as follows:
1. auto storage class
2. static storage class
3. register storage class
4. extern storage class
1. auto storage class:
➔ The default storage class of all local variables (variables declared inside block or function) is auto storage
class.
➔ Variable of auto storage class has the following properties:
77
➔ The static storage class is used to create variables that hold value beyond its scope until the end of the
program.
➔ The static variable allows to initialize only once and can be modified any number of times.
➔ Variable of static storage class has the following properties:
78
➔ The register storage class is used to specify the memory of the variable that has to be allocated in CPU
Registers.
➔ The register variables enable faster accessibility compared to other storage class variables.
➔ As the number of registers inside the CPU is very less we can use very less number of register variables.
➔ Variable of register storage class has the following properties:
79
➔ The default storage class of all global varibles (variables declared outside function) is external storage class.
➔ Variable of external storage class has the following properties:
80
➔ File handing in C is the process in which we create, open, read, write, and close operations on a file.
➔ C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform
input, output, and many different C file operations in our program.
➔ The operations using the C program are done on a prompt/terminal which is not stored anywhere.
➔ The output is deleted when the program is closed. But in the software industry, most programs are written to
store the information fetched from the program.
➔ The use of file handling is exactly what the situation calls for.
➔ In order to understand why file handling is important, a few features of using files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high
reusability.
Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed
coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part
of a file using few instructions which saves a lot of time and reduces the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything
simultaneously in a program.
A file can be classified into two types based on the way the file stores the data. They are as follows:
1. Text Files
2. Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
81
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is stored
in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
The different possible operations that we can perform on a file in C such as:
➔ Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
➔ Opening an existing file – fopen()
➔ Reading from file – fscanf() or fgets()
➔ Writing to a file – fprintf() or fputs()
➔ Moving to a specific location in a file – fseek(), rewind()
➔ Closing a file – fclose()
82
A file pointer is a reference to a particular position in the opened file. It is used in file handling to perform all file
operations such as read, write, close, etc. We use the FILE macro to declare the file pointer variable. The FILE macro is
defined inside <stdio.h> header file.
FILE* pointer_name;
Q 18. Explain how to open a file and File opening modes in C language.
The fopen() function is used with the filename or file path along with the required access modes.
Syntax of fopen()
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise, full path.
Return Value
File opening modes or access modes specify the allowed operations on the file to be opened. They are passed as an
argument to the fopen() function. Some of the commonly used file access modes are listed below:
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
r
points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
w
file is created. Returns NULL, if unable to open the file.
Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it
wb
will be created.
83
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.
Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be
ab
created.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to
r+
the first character in it. Returns NULL, if unable to open the file.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
w+
Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file
wb+
does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a+ points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open the file.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
There are many functions in the C library to open, read, write, search and close the file. A list of file functions are
given