UNIT-IV PRG in C
UNIT-IV PRG in C
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function
with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Definition
The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The
below example serves as both a function definition and a declaration.
Syntax
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
1
Function Call
A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum function.
After the function call sum of a and b is returned and control is also returned back to the main
function of the program.
Example of C
Function
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
int add = sum(10, 30);
printf("Sum is:
%d", add);return
0;
}
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
2
1. Library Function
A library function is also referred to as a “built-in function”. A compiler package already exists
that contains these functions, each of which has a specific meaning and is included inthe package.
Built-in functions have the advantage of being directly usable without being defined, whereas
user-defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(),
strcpy() etc.Advantages of
C library functions
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they
always work.
Example:
#include <math.h>
#include <stdio.h>
int main()
{
double Number;
Number = 49;
double squareRoot = sqrt(Number);
printf("The Square root of %.2lf = %.2lf",Number, squareRoot);
return 0;
}
double squareRoot = sqrt(Number);
printf("The Square root of %.2lf = %.2lf",Number, squareRoot);
return 0;
}
Output
The Square root of 49.00 = 7.00
3
Advantages of User-Defined Functions
Changeable functions can be modified as per need.
The Code of these functions is reusable in other programs.
These functions are easy to understand, debug and maintain.
Example:
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
int a = 30, b = 40;
int res = sum(a, b);
printf("Sum is: %d", res);return 0;
}
Categories of Functions.
Functions can be differentiated into 4 types according to the arguments passed
and valuereturns these are:
1. Function with arguments and return value
2. Function with arguments and no return value
3. Function with no arguments and with return value
4. Function with no arguments and no return value
Example:
#include <stdio.h>
#include <string.h>
int function(int, int[]);
int main()
{
int i, a = 20;
int arr[5] = { 10, 20, 30, 40, 50 };
a = function(a, &arr[0]);
printf("value of a is %d\n", a);for (i = 0; i < 5; i++)
{
printf("value of arr[%d] is %d\n", i, arr[i]);
}
return 0;
}
int function(int a, int* arr)
{
int i;
a = a + 20;
arr[0] = arr[0] + 50;
4
arr[1] = arr[1] + 50;
arr[2] = arr[2] + 50;
arr[3] = arr[3] + 50;
arr[4] = arr[4] + 50;
return a;
}
Output
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
Example:
#include <stdio.h>
void function(int, int[], char[]);
int main()
{
int a = 20;
int ar[5] = { 10, 20, 30, 40, 50 };
char str[30] = "geeksforgeeks";
function(a, &ar[0], &str[0]);
return 0;
}
void function(int a, int* ar, char* str)
{
int i;
printf("value of a is %d\n\n", a);
for (i = 0; i < 5; i++)
{
printf("value of ar[%d] is %d\n", i, ar[i]);
}
printf("\nvalue of str is %s\n", str);
}
}
Output
value of a is 20
value of ar[0] is 10
value of ar[1] is 20
value of ar[2] is 30
value of ar[3] is 40
value of ar[4] is 50
5
3. 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 fromthe
called function.
Example:
#include <stdio.h>
void value(void);
void main()
{
value();
}
void value(void)
{
float year = 1, period = 5, amount = 5000,inrate = 0.12;
float sum;
sum = amount;
while (year <= period)
{
sum = sum * (1 + inrate);year = year + 1;
}
printf(" The total amount is :%f", sum);
}
Output
The total amount is :8811.708984
Example:
#include <math.h>
#include <stdio.h>
int sum();
int main()
{
int num;
num = sum();
printf("Sum of two given values = %d", num);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = sqrt(a) + sqrt(b);
return sum;
}
Output
Sum of two given values = 16
6
Passing Parameters to Functions
The data passed when the function is being invoked is known as the Actual parameters. In the
below program, 10 and 30 are known as actual parameters. Formal Parameters are the variable
and the data type as mentioned in the function declaration. In the below program, a and b are
known as formal parameters.
Example:
#include <stdio.h>
void swap(int var1, int var2)
{
int temp = var1;var1 = var2; var2 = temp;
}
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Output
Before swap Value of var1 and
var2 is: 3, 2After swap Value of
var1 and var2 is: 3, 2
7
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the same locations, so
any changes made inside the function are reflected in the caller’s actualparameters.
Example:
#include <stdio.h>
void swap(int *var1, int *var2)
{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Output
Before swap Value of var1 and
var2 is: 3, 2After swap Value of
var1 and var2 is: 2, 3
Storage Classes in C
What are storage classes in C?
The four different storage classes in C program are auto, register, extern, and static. Storage class
specifier for C language can be used for defining variables or functions as well as parameters. Auto
can be used for any local variable that is defined within the block or function.
o Automatic
o External
o Static
o Register
8
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are defined.
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple function
calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
9
{
sum(); // The static variables holds their value between multiple function calls.
}
}
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers depending
upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the register
variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register.
However, it is compiler?s choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
Example 1
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
}
Output:
0
External
o The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and
intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will
show an error.
10
Example 1
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pog
ram or not.
printf("%d",a);
}
int a = 20;
}
Output
20
Character Arrays
What are character arrays in C?
A Character array is a derived data type in C that is used to store a collection of characters or
strings.
A char data type takes 1 byte of memory, so a character array has the memory of the number of
elements in the array. (1* number_of_elements_in_array).
Each character in a character array has an index that shows the position of the character in the
string.
The first character will be indexed 0 and the successive characters are indexed 1,2,3 etc...
The null character \0 is used to find the end of characters in the array and is always stored in
the index after the last character or in the last index.
Syntax
There are many syntaxes for creating a character array in c.
The most basic syntax is,
char name[size];
The name depicts the name of the character array and size is the length of the character array.
The size can be greater than the length of the string but can not be lesser. If it is lesser then the
full string can't be stored and if it is greater the remaining spaces are just left unused.
Example
Dynamic memory allocation is an efficient way to allocate memory for a variable in c.
The memory is allocated in the runtime after getting the number of characters from the user.
It uses pointers, which are structures that point to an address where the real value of the
variable is stored.
The malloc() function is used for dynamic memory allocation. Its syntax is,
sizeof(datatype)
The malloc method is present in the header stdlib.h.
Example
#include<stdio.h>
#include<stdlib.h>
int main()
{
11
int n, i;
char *arr;
printf("Enter number of characters to store: ");
scanf("%d", &n); //getting size
arr = (char*)malloc(n*sizeof(char));
printf("Enter the string: ");
for(i=0; i < n; i++)
{
scanf(" %c",arr+i);
}
printf("\nThe string entered is: \n\n");
for(i = 0; i < n; i++)
{
printf("%c ", arr[i]);
}
printf("\The elements at index 2: %c ",arr[2]);
return 0;
}
Output:
Enter the number of characters to store: 9
Enter the string: character
The string entered is:
character
The elements at index 2: a
C string functions
The C string functions are built-in functions that can be used for various operations and
manipulations on strings. These string functions can be used to perform tasks such as string copy,
concatenation, comparison, length, etc. The <string.h> header file contains these string functions.
String Length
For example, to get the length of a string, you can use the strlen() function:
Example
#include <stdio.h>
#include <string.h>
int main()
{
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
return 0;
}
Output
26
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
12
Example
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello ";
char str2[] = "World!";
// Concatenate str2 to str1 (the result is stored in str1)
strcat(str1, str2);
// Print str1
printf("%s", str1);
return 0;
}
Output
Hello World!
Copy Strings
To copy the value of one string to another, you can use the strcpy() function:
Example
include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello World!";
char str2[20];
// Copy str1 to str2
strcpy(str2, str1);
// Print str2
printf("%s", str2);
return 0;
}
Output
Hello World!
Compare Strings
To compare two strings, you can use the strcmp() function.
It returns 0 if the two strings are equal, otherwise a value that is not 0:
Example
#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
13
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output
Enter 1st string :hello
Enter 2nd string: hello
String are equal
String Reverse
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.
Example
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output
Enter string :javatpoint
String is :javatpoint
Rverse String is :tnioptavaj
Nested Function
A nested function is a function defined inside the definition of another function. It can be defined
wherever a variable declaration is permitted, which allows nested functions within nested functions.
Within the containing function, the nested function can be declared prior to being defined by using
the auto keyword.
Example
#include <stdio.h>
void outerFunction()
{
int x = 10;
void innerFunction()
{
printf("Inner function: %d\n", x);
}
innerFunction();
}
14
int main()
{
outerFunction();
return 0;
}
Output
Inner function: 10
Explanation
In this example, outerFunction() is defined with a nested function innerFunction() inside it. x is a local
variable of outerFunction(). innerFunction() is called within outerFunction(). Inside innerFunction(), it
prints the value of x.
Recursive Function
What is a recursive function in C?
The recursion process in C refers to the process in which the program repeats a certain section of code in a
similar way. Thus, in the programming languages, when the program allows the user to call any
function inside the very same function, it is referred to as a recursive call in that function.
15
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
Output:
Enter a number: 6
Factorial of 5 is:720
16