UNIT-3
UNIT-3
INSTITUTE OF SCIENCE
M ANDTECHNOLOGY,
CHENNAI.
Functions with and without Arguments and Return Values – Passing Array to
function with return type – Recursion Function
Two Dimensional Array requires Two Subscript Variables
Two Dimensional Array stores the values in the form of matrix.
One Subscript Variable denotes the “Row” of a matrix.
Another Subscript Variable denotes the “Column” of a matrix.
Row 2 : { 5 , 2 },
Row 3 : {6,5}
We have initialized each row independently
a[0][0] = 1
A[0][1] = 4
Method 2 : COMBINE ASSIGNMENT
Initialize all Array elements but initialization is much
straight forward. All values are assigned sequentially
and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
So here it automatically assigns that number 3 has row and
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {9, 1, 6, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};
int main()
{
int i, j, k, test[2][3][2]; // this array can store 12 elements
scanf("%d",
}
}
printf("\nDisplaying values:\n");//Displaying values with
proper index.
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k )
{
printf("test[%d][%d][%d] = %d\n", i, j, k,
test[i][j][k]);
}
}
}
return 0;
OUTPUT: Displaying
Enter 12 values: Values:
test[0][0][0] = 1
1 test[0][0][1] = 2
2 test[0][1][0] = 3
3 test[0][1][1] = 4
test[0][2][0] = 5
4 test[0][2][1] = 6
5 test[1][0][0] = 7
6 test[1][0][1] = 8
test[1][1][0] = 9
7 test[1][1][1] = 10
8 test[1][2][0] = 11
9 test[1][2][1] = 12
10
11
3.3 ARRAY PROGRAMS –
2D
a) Basic 2d array program
b) Store and display values
c) Sum of two matrices using Two dimensional
arrays
d) Transpose of Matrix
e) Multiplication of 2d matrices.
#include<stdio.h> //Displaying array elements
int main(){ printf("Two Dimensional
int disp[2][3]; /* 2D array elements:\n");
array declaration*/ for(i=0; i<2; i++) {
int i, j; /*Counter for(j=0;j<3;j++) {
variables printf("%d ",
for loop*/ disp[i][j]); if(j==2){
for(i=0; i<2; i++) { printf("\n");
for(j=0;j<3;j++) { }
printf("Enter value for } }
disp[%d][%d]:", i, j); return 0; }
scanf("%d", &disp[i][j]);
}}
OUTPUT
Enter value for
disp[0][0]:1 Enter value
for disp[0][1]:2 Enter
value for disp[0][2]:3
Enter value for
disp[1][0]:4 Enter value
for disp[1][1]:5 Enter
value for disp[1][2]:6
Two Dimensional array
elements: 1 2 3
456
#include <stdio.h> printf("\nDisplaying values:
const int CITY = 1; \n\n");
const int WEEK = for (int i = 0; i < CITY; ++i) {
7; int main() for(int j = 0; j < WEEK;
{ ++j)
int {
temperature[CITY][WEEK]; %d\n",printf("City
i+1,j+1, %d, Day %d =
for (int i = 0; i < CITY; ++i) { temperature[i][j])
for(int j = 0; j < WEEK; ++j) { ;
printf("City %d, Day %d: ", }
i+1, j+1); }
scanf("%d", return 0;
&temperature[i][j]) }
;
OUTPUT
City 1, Day 1: 33 Displaying values:
City 1, Day 2: 34 City 1, Day 1 = 33
City 1, Day 3: 35 City 1, Day 2 = 34
City 1, Day 4: 33 City 1, Day 3 = 35
City 1, Day 5: 32 City 1, Day 4 = 33
City 1, Day 6: 31 City 1, Day 5 = 32
City 1, Day 7: 30 City 1, Day 6 = 31
City 1, Day 7 = 30
#include <stdio.h> printf("Enter elements of 2nd
int main() matrix\n");
{ for(i=0; i<2; ++i)
float a[2][2], b[2][2], c[2][2]; for(j=0; j<2; ++j)
int i, j; // Taking input using nested {
for loop printf("Enter b%d%d: ", i+1, j+1);
printf("Enter elements of 1st scanf("%f", &b[i][j]);
matrix\n"); }// adding corresponding elements of
for(i=0; i<2; ++i) two arrays
for(j=0; j<2; ++j) for(i=0; i<2; ++i)
{ for(j=0; j<2; ++j)
printf("Enter a%d%d: ", i+1, j+1); {
scanf("%f", &a[i][j]); c[i][j] = a[i][j] + b[i][j];
} // Taking input using nested for }
loop
OUTPUT:
Enter elements of 1st matrix
// Displaying the sum Enter a11: 2;
printf("\nSum Of Matrix:"); Enter a12: 0.5;
for(i=0; i<2; ++i) Enter a21: -1.1;
for(j=0; j<2; ++j) Enter a22: 2;
Enter elements of 2nd matrix
{
Enter b11: 0.2;
printf("%.1f\t", c[i][j]); Enter b12: 0;
if(j==1) Enter b21: 0.23;
printf("\n"); Enter b22: 23;
} Sum Of Matrix:
return 0; 2.2 0.5
-0.9 25.0
}
#include <stdio.h> printf("\nEntered Matrix: \n");
int main() for(i=0; i<r; ++i)
{ for(j=0; j<c; ++j)
int a[10][10], transpose[10][10], r, c, {
i, j; printf("%d ", a[i][j]);
printf("Enter rows and columns if (j == c-1)
of printf("\n\n");
matrix: "); %d",
scanf("%d &r, &c); // }// Finding the transpose
Storing elements matrix a of
printf("\nEnter elements of for(i=0; i<r; ++i)
matrix:\n"); for(j=0; j<c; ++j)
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j) transpose[j][i] = a[i][j];
{ }
printf("Enter element a%d%d:
",i+1, j+1);
scanf("%d", &a[i][j]); }
output
// Displaying the transpose of matrix Enter rows and columns of matrix: 2 3
a printf("\nTranspose of Enter element of matrix:
Matrix:\n"); for(i=0; i<c; ++i) Enter element a11: 2
for(j=0; j<r; ++j) Enter element a12: 3
{ Enter element a13: 4
printf("%d ",transpose[i][j]); Enter element a21: 5
if(j==r-1) Enter element a22: 6
printf("\n\n"); Enter element a23: 4
} Entered Matrix:
return 0; 2 34
} 5 64
Transpose of
Matrix: 2 5
3 6
4 4
#include printf("Enter number of rows
<stdio.h> int and columns of second
main() matrix\n"); scanf("%d%d", &p, &q);
{ int m, n, p, q, c, d, k, sum = 0; for (c = 0; c < p; c++)
intfirst[10][10], second[10][10], for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
multiply[10][10];
for (c = 0; c < m; c++) {
printf("Enter number of rows and for (d = 0; d < q; d++) {
columns of first matrix\n"); for (k = 0; k < p; k++) {
scanf("%d%d", &m, &n); sum = sum+
printf("Enter elements of first first[c][k]*second[k][d];
matrix\n"); }
for (c = 0; c < m; c++) multiply[c][d] = sum;
for (d = 0; d < n; d++) sum = 0;
scanf("%d", &first[c][d]); }}
printf("Product of the Enter the number of rows
columns of second matrix:
and
matrices:\n"); 3
for (c = 0; c < m; c++) 3
{ for (d = 0; d < q; Enter elements of
d++) the second
printf("%d\t", multiply[c][d]); matrix:
112
printf("\n"); 211
} } 121
Product of entered matrices:-
} return 0; 5 3 4
OUTPUT 3 3 2
Enter the number of rows and columns 3 4 5
of first matrix: 33
Enter the elements of first matrix: 1 2 0
011
201
4. ARRAY CONTIGUOUS MEMORY
● When Big Block of memory is reserved or allocated then that
memory block is called as Contiguous Memory Block.
● Alternate meaning of Contiguous Memory is continuous
memory.
● Suppose inside memory we have reserved 1000-1200 memory
addresses for special purposes then we can say that these 200
blocks are going to reserve contiguous memory.
How to allocate contiguous
memory:
● Using static array declaration.
● Using alloc() / malloc() function to allocate big chunk of
memory dynamically.
When process try to refer a part of the memory then it will firstly
refer the base address from base register and then it will refer
relative address of memory location with respect to base address
3.5 ADVANTAGE AND LIMITATIONS OF
1.ARRAY
Advantages:
● It is better and convenient way of storing the data of same
datatype with same size.
● It allows us to store known number of elements in it.
● It allocates memory in contiguous memory locations for its
elements. It does not allocate any extra space/ memory for its
elements. Hence there is no memory overflow or shortage of
memory in arrays.
● Iterating the arrays using their index is faster compared to any
other methods like linked list etc.
● It allows to store the elements in any dimensional array -
supports multidimensional array.
3.5.2 Limitations of
A)Array:
Static Data
− Array is Static data Structure
− Memory Allocated during Compile time.
− Once Memory is allocated at Compile Time it Cannot be
Changed during Run-time.
B) Can hold data belonging to same Data types
− Elements belonging to different data types cannot be stored
in array because array data structure can hold data
belonging to same data type.
− Example : Character and Integer values can be stored inside
separate array but cannot be stored in single array
C) Inserting data in Array is Difficult
− Inserting element is very difficult because before inserting
element in an array have to create empty space by shifting
other elements one position ahead.
− This operation is faster if the array size is smaller, but same
operation will be more and more time consuming and non-
efficient in case of array with large size.
D) Deletion Operation is difficult
− Deletion is not easy because the elements are stored in
contiguous memory location.
− Like insertion operation , we have to delete element from the
array and after deletion empty space will be created and thus
we need to fill the space by moving elements up in the array.
E) Bound Checking
− If we specify the size of array as ‘N’ then we can access elements upto
‘N-1’ but in C if we try to access elements after ‘N-1’ i.e Nth element or
N+1th element then we does not get any error message.
− Process of Checking the extreme limit of array is called Bound checking
and C does not perform Bound Checking.
− If the array range exceeds then we will get garbage value as result.
E) Shortage of Memory
− Array is Static data structure. Memory can be allocated at compile time
only Thus if after executing program we need more space for storing
additional information then we cannot allocate additional space at run
time.
− Shortage of Memory , if we don’t know the size of memory in advance
F) Wastage of Memory
− Wastage of Memory , if array of large size is defined.
3.6 ARRAY CONSTRUCTION FOR REAL-TIME
APPLICATION COMMON PROGRAMMING ERRORS
Bound checking - C Does not Support Bound Checking i.e if we store City
with size greater than 30 then C will not give you any
error
Data type - char
Maximum size - 30
Precautions to be taken while declaring Character Variable :
● String / Character Array Variable name should be legal C Identifier.
● String Variable must have Size specified.
− char city[];
● Above Statement will cause compile time error.
− Do not use String as data type because String data type
is included in later languages such as C++ / Java. C does
not support String data type
− String city;
● When you are using string for other purpose than accepting and
printing data then you must include following header file in your
code –
− #include<string.h>
2. Initializing String [Character Array] :
● Whenever we declare a String then it will contain
garbage values inside it. We have to initialize String or
Character array before using it. Process of Assigning
some legal default data to String is Called Initialization of
String. There are different ways of initializing String in C
Programming –
1)Initializing Unsized Array of Character
2)Initializing String Directly
3)Initializing String Using Character Pointer
Way 1 : Unsized Array and Character
● Unsized Array : Array Length is not specified
while initializing character array using this approach
● Array length is Automatically calculated by Compiler
● Individual Characters are written inside Single Quotes ,
Separated by comma to form a list of characters.
Complete list is wrapped inside Pair of Curly braces
● NULL Character should be written in the list because it is
ending or terminating character in the String/Character
Array
● char name [] = {'P','P','S','\0'};
Way 2 : Directly initialize String Variable
● In this method we are directly assigning String to
variable by writing text in double quotes.
● In this type of initialization , we don’t need to put NULL
or Ending / Terminating character at the end of string. It
is appended automatically by the compiler.
● char name [ ] = "PPS";
Way 3 : Character Pointer Variable
● Declare Character variable of pointer type so that it can
hold the base address of “String”
● Base address means address of first array
element i.e (address of name[0] )
● NULL Character is appended Automatically
● char *name = "PPS";
9. STRING FUNCTIONS
− − Strcmp()
− gets()
− puts() − Sprintf()
− Getchar() − Sscanf()
− Putchar() − Strrev()
− Printf() − Strcpy()
− Atoi() − Strstr()
− Strlen() − strtok()
− Strcat ()
3.9.1 GETS():
Syntax for Accepting String :
char * gets ( char * str );
OR gets(
<variable-name> )
Example :
#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name :
"); gets(name); }
Output:
Explanation :
❑ Whenever gets() statement encounters then characters entered by user
(the string with spaces) will be copied into the variable.
❑ If user start accepting characters , and if new line character appears
then the newline character will not be copied into the string variable(i.e
name).
function.
● We have to explicitly mention Character.
Way 2 : Taking Variable as Parameter
putchar(a);
// Display Character Stored in a
❑ Input Parameter is Variable of Type “Character”.
Syntax :
Way 1 : Messaging
printf (" Type your Message / Instruction " ) ;
Way 2 : Display String
printf ("Name of Person is %s ", name ) ;
Notes or Facts :
printf is included in header file “stdio.h”
As name suggest it used for Printing or Displaying Messages or
Instructions Uses :
● Printing Message
● Printing Results
3.10.1 ATOI
Atoi = A to I = Alphabet to Integer
FUNCTION:
●
Example :
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n",
value); return 0;
Output :
Value : 100
Significance :
● Can Convert any String of Number into Integer Value that can Perform
Point Explanation
No of - 1
Parameters - Character Array Or String
Parameter Taken - Integer
Return Type - Compute the Length of the String
Description - string.h
Header file
Different Ways of Using strlen() :
● There are different ways of using strlen function. We can pass
Syntax :
char* strlen ( char * s1, char * s2);
Ways of Using Strcat Function :
Way 1 : Taking String Variable as Parameter
char str1[20] = “Don” , str2[20] =
“Bosqo”; strcat(str1,str2);
puts(str1);
● It returns integer .
Syntax :
int strcmp ( char *s1, char *s2 ) ;
Return Condition
Type - String1 < String2
-ve Value - String1 > String2
+ve Value - String1 = String2
0 Value
Example 1 : Two strings are Equal
char s1[10] = "SAM",s2[10]="SAM"
;
int len;
len = strcmp
(s1,s2); Output
0
/*So the output willbe 0. if u want to print the string
then give condition like*/
char s1[10] = "SAM",s2[10]="SAM" ;
int len;
len = strcmp
(s1,s2); if (len == 0)
printf ("Two Strings are Equal");
Output:
Example 2 : String1 is Greater than String2
Reason :
ASCII value of “SAM” is smaller than
“sam”
ASCII value of ‘S’ is smaller than ‘s’
Example 3 : String1 is Smaller than String1
Reason :
ASCII value of “SAM” is greater than
“sam”
ASCII value of ‘S’ is greater than ‘s’
1. SPRINTF FUNCTION:
● sends formatted output to String.
Features :
● Output is Written into String insteadof Displaying it
on the Output Devices.
● Return value is integer ( i.e Number of characters actually placed
Syntax :
int sprintf(char *buf,char format,arg_list);
Example :
int age = 23 ;
char str[100];
sprintf( str , "My age is
%d",age); puts(str);
Output:
My age is 23
Analysis of Source Code: Just keep in mind that
❑ Assume that we are using printf then we get output “My age is
23”
❑ What does printf does ? —– Just Print the Result on the Screen
❑ Similarly Sprintf stores result “My age is 23” into string str instead
of printing it.
3.11.2 SSCANF FUNCTION:
Syntax :
int sscanf(const char *buffer, const char *format[, address, ...]);
Output:
string found
First string “test” in “This is a test string” to “test string”.
Example 2
Parameters as String initialized using Pointers
#include<stdio.h>
#include<string.h>
int main(void)
{
char *str1 = "c4learn.blogspot.com", *str2 = "spot",
*ptr; ptr = strstr(str1, str2);
printf("The substring is: %sn",
ptr); return 0;
}
Output:
The substring is: spot.com
Example 3
Passing Direct Strings
#include<stdio.h>
#include<string.h>
void main()
{
char *ptr;
ptr =
strstr("c4learn.blogspot.com","spot");
printf("The substring is: %sn", ptr);
}
Output:
The substring is: spot.com
3.11.4 STRREV():
● reverses a given string in C language. Syntax for strrev( ) function is
given below.
char *strrev(char *string);
● strrev() function is nonstandard function which may not available in
standard library in C.
Algorithm to Reverse String in C :
Start
Take 2 Subscript Variables ‘i’,’j’
‘j’ is Positioned on Last Character
‘i’ is positioned on first character
str[i] is interchanged with str[j]
Increment ‘i’
Decrement ‘j’
If ‘i’ > ‘j’ then goto step 3
Stop
Example
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev() :%s\n",name);
printf("String after strrev(%s",
strrev(name)); return 0;
}
Output:
String before strrev() :
Hello String after strrev() :
olleH
5. STRCPY FUNCTION:
Copy second string into First
❑ It returns string.
Syntax :
char * strcpy ( char *string1, char *string2 )
;
● strcpy ( str1, str2) – It copies contents of str2 into str1.
● strcpy ( str2, str1) – It copies contents of str1 into str2.
● If destination string length is less than source string,
string.
MIKE
MIKE
Example 2
#include <stdio.h>
#include
<string.h> int
{main( )
char source[ ] = "hihello" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source )
; printf ( "\ntarget string = %s", target )
; strcpy ( target, source ) ;
printf("target string after strcpy()=%s",target)
; return 0; }
Output
source string = hihello
target string =
target string after strcpy( ) = hihello
6. STRTOK FUNCTION
● tokenizes/parses the given string using delimiter.
Syntax
char * strtok ( char * str, const char * delimiters );
For example, we have a comma separated list of items from a file
and we want individual items in an array.
{
char str[] = "Problem_Solving_in_c";//Returns first token
char* token = strtok(str, "_");//Keep printing tokens while
one of the delimiters present in
str[]. while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL,
"_");
}return 0;
}
Output:
Problem
Solving
in
C
12. ARITHMETIC CHARACTERS ON STRING
● C Programming Allows you to Manipulate on String
● Whenever the Character is variable is used in the expression
then it is automatically Converted into Integer Value called
ASCII value.
● All Characters can be
with that
Manipulated Integer
Value.(Addition,Subtraction)
Examples :
ASCII value of : ‘a’ is 97
Possible Ways of Manipulation
:Way 1:Displays ASCII value[ Note that %d in Printf]
char x = 'a';
printf("%d",x); // Display Result = 97
Way 2 :Displays Character value[Note that %c in
Printf] char x = 'a';
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.
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function
signature.
❑ Function with integer argument and integer as return type is represented using
syntax int square(int);
❑In the below example we have written function with no argument and no return
type void display(void);
❑In below example we have delclared function with no argument and integer as
has to do. To use a function, you will have to call that function to
perform
❑If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parameters of the function.
❑Formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
❑ While calling a function, there are two ways in which arguments can be
passed to a function −
❑By default, C uses call by value to pass arguments. In general, it means
the code within a function cannot alter the arguments used to call the
function.
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
Sr.No. CHENNAI.
Call Type & Description
1 Call by value This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
/* function definition to swap the values
*/ void swap (int x, int y)
{
int temp; temp = x;
/* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y
*/ return; }
2 Call by reference This method copies the address of an argument into the
formal parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the parameter
affect the argument.
/* function definition to swap the values */
void swap (int *x, int *y)
{
int temp;
temp =
*x;
*x = *y;
*y = temp;
return; }
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY, CHENNAI.
1. CALL BY VALUE
❑While Passing Parameters using call by value , xerox copy of original parameter is
created and passed to the called function.
❑Any update made inside method will not affect the original value of variable in
calling function.
❑In the above example num1 and num2 are the original values and xerox copy of
these values is passed to the function and these values are copied into
number1,number2 variable of sum function respectively.
❑As their scope is limited to only function so they cannot alter the values inside
main function.
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
#include <stdio.h>
void swap(int x, int y); /* function declaration
*/ int main ()
{
int a = 100; /* local variable definition */
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );/*calling a function to swap the values
*/ swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Output:
Before swap, value of a :100
Before swap, value of b
:200 After swap, value of a
:100 After swap, value of b
:200
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
2. CALL BY REFERENCE
❑The call by reference method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. It means the
changes made to the parameter affect the passed argument.
❑ Function accepts argument but it does not return a value back to the calling Program
.
❑ It is Single ( One-way) Type Communication
❑ Generally Output is printed in the Called function
Function declaration : void function();
Function call : function();
Function definition : void function() { statements; }
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n; printf("Enter a positive integer:
"); scanf("%d",&n);
// n is passed to the function checkPrimeAndDisplay(n);
return 0;
}
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY, CHENNAI.
// void indicates that no value is returned from the function
void checkPrimeAndDisplay(int n)
{
int i, flag = 0;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0){
flag = 1;
break; }
}
if(flag == 1)
printf("%d is not a prime
number.",n); else
printf("%d is a prime number.", n);
}
OUTPUT
Enter a positive integer :
4 4 is not a prime
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
3.15.2 FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE IN C
When a function has no arguments, it does not receive any data from the
calling function. Similarly when it does not return a value, the calling function
does not receive any data from the called function.
Syntax :
Function declaration : void function();
Function call : function();
Function definition : void function()
{
statements;
}
#include<stdio.h>
void area(); // Prototype Declaration
void main()
{
area();
}
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
void area()
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
printf("Area of Circle =
%f",area_circle);
}
Output :
Enter the radius : 3
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
int sum()
{
int a = 50, b = 80, sum;
sum = a + b;
return sum;
}
OUTPUT
Sum of two given values = 130
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY, CHENNAI.
3.16.2 FUNCTION WITH ARGUMENTS AND RETURN VALUE
Syntax :
Function declaration : int function ( int );
Function call : function( x );
Function definition: int function( int x ) { statements; return x; }
#include<stdio.h>
float calculate_area(int);
int main()
{
int radius;
float area;
printf("\nEnter the radius of the circle : ");
scanf("%d",&radius);
area = calculate_area(radius);
printf("\nArea of Circle : %f ",area);
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
return(0);
}
float calculate_area(int radius)
{
float areaOfCircle;
areaOfCircle = 3.14 * radius * radius;
return(areaOfCircle);
}
Output:
Enter the radius of the circle :
2 Area of Circle : 12.56
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
17. PASSING ARRAY TO FUNCTION IN C
Array Definition :
Array is collection of elements of similar data types .
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,CHENNAI.
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing entire array
.....");
}
output
Enter the array elements : 1 2 3 4 5
Passing entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
Tabular Explanation :
Consider following array
Element Passed
Iteration Value of Element
to Function
1 arr[0] 11
2 arr[1] 22
3 arr[2] 33
4 arr[3] 44
5 arr[4] 55
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY, CHENNAI.
C Program to Pass Array to Function Element by Element
:
#include< stdio.h>
#include< conio.h>
void fun(int num)
{
printf("\nElement : %d",num);
}
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing array element by element.....");
for(i=0;i< 5;i++)
fun(arr[i]);
getch(); }
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
Output : CHENNAI.
Enter the array elements : 1 2 3 4 5
Passing array element by
element..... Element : 1
Element : 2
Element : 3
Element : 4
Element : 5
int factorial(int n)
{
if(n==0)
return(1);
else
return( n * factorial(n-1));
}
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
Example: CHENNAI.
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Output
Enter a positive integer: 3 6
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
SRM INSTITUTE OF SCIENCE
ANDTECHNOLOGY,
CHENNAI.
Warning of using recursive function in C Programming :
❑Recursive function must have at least one terminating condition that can
be satisfied.
❑Otherwise, the recursive function will call itself repeatably until the run