Module-3
Module-3
Function
It is a building block that contains set of programming statements to
perform a particular task.
Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
Function Declaration
Syntax:
Syntax:
Ex:
int sum (int a, int b)
{
Variable declaration;
Input statement; Function Body
Processing statements;
Output statements;
}
Function Return value
--If the function doesn’t return any value, then the return type can be
mentioned as ‘void’.
Example:
void show()
{
printf(“Hello”);
}
--If the function return any specific value, then the corresponding
datatype can be mentioned as the return type can be mentioned such
as int, float, char, double etc.
• Library Function
The functions which are already defined in C library/header files.
Example: printf(), scanf(), gets(), puts(), getchar(), putchar(), sqrt(),
pow(), tolower(), toupper(), islower(), isupper()
• User Defined Function
The functions which are created by the programmer.
These functions must be declared before usage.
These functions’ definition must be written by the programmer.
Function Declaration, Call, Definition Example:
#include<stdio.h>
int sum(int a, int b); Function Declaration
int main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d", &a,&b);
result = sum(a,b); Function Call
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
Function Body
int r;
r=a+b;
return r;
}
Categories of Function Prototype/Declaration
Example 1
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b); Output
printf("\nThe sum is : %d",result);
} Going to calculate the sum of two
int sum(int a, int b) numbers:
Enter two numbers:10
{
20
return a+b; The sum is : 30
}
#include<stdio.h> Example 2 int even_odd(int n)
int even_odd(int); {
void main() if(n%2 == 0)
{ {
int n,flag=0; return 1;
printf("\nGoing to check whether a number is }
even or odd"); else
printf("\nEnter the number: "); {
scanf("%d",&n); return 0;
flag = even_odd(n); }
if(flag == 0) }
{
printf("\nThe number is odd");
} Output
else
{ Going to check whether a number is even or odd
printf("\nThe number is even"); Enter the number: 100
} The number is even
}
Formal Parameter & Actual Parameter
1. Actual Parameters :
The arguments that are passed in a function call are called actual
arguments. These arguments are defined in the calling function.
These are the variables or expressions referenced in the parameter
list of a subprogram call. There is no need to specify datatype in
actual parameter.
2. Formal Parameters :
These are the variables or expressions referenced in the parameter list
of a subprogram specification. The datatype of the receiving value must
be defined. The scope of formal arguments is local to the function
definition in which they are used.
Call by Value and Call by Reference
Functions can be invoked in two ways: Call by Value or Call by Reference. These two
ways are generally differentiated by the type of values passed to them as parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied
to function’s formal parameters and the two types of parameters are stored in different
memory locations. So any changes made inside functions are not reflected in actual
parameters of the caller.
Call by Reference: Both the actual and formal parameters refer to the same locations, so
any changes made inside the function are actually reflected in actual parameters of the
caller.
// C program to illustrate call by value
#include<stdio.h>
void swapx(int x, int y);
int main()
{
int a = 10, b = 20;
swapx(a, b);
printf("a=%d b=%d\n", a, b);
Output:
return 0;
x=20 y=10
}
a=10 b=20
void swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%d\n", x, y);
}
// C program to illustrate Call by Reference
#include <stdio.h>
void swapx(int*, int*);
int main()
{
int a = 10, b = 20;
swapx(&a, &b);
printf("a=%d b=%d\n", a, b); Output:
return 0; x=20 y=10
} a=20 b=10
void swapx(int* x, int* y)
{
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%d\n", *x, *y);
}
Function that returns multiple values
We can return more than one values from a function by using the
method called “call by address”, or “call by reference”.
In the invoker function, we will use two variables to store the results,
and the function will take pointer type data. So we have to pass the
address of the data.
Example Program
#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) ;
main() {
int a = 76, b = 10;
int q, r;
div(a, b, &q, &r);
printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}
void div(int a, int b, int *quotient, int *remainder)
{
*quotient = a / b;
*remainder = a % b;
}
Pass arrays to a function in C
int main() {
int ageArray[] = {2, 8, 4, 12};
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
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]);
}}}
Storage Classes in C: Auto, Extern, Static, Register (Examples)
The lifetime of a variable defines the duration for which the computer allocates
memory for it (the duration between allocation and deallocation of memory).
#include<stdio.h>
main ( ){
auto int i=1;{
auto int i=2;{
auto int i=3;
printf ("%d",i)
}
printf("%d", i);
}
printf("%d", i);
}
321
Storage Class Specifiers
There are four types of storage classes in C that are known as
storage class specifiers.
• Automatic (auto)
• Register (register)
• External (extern)
• Static (static)
Example:
auto int x;
What are the Types of Storage Classes in C?
There are total four types of standard storage classes. The table below
represents the storage classes in C.
1) auto
The auto keyword is applied to all local variables automatically. It is the default
storage class that is why it is known as automatic variable. It's default value is
Garbage Value.
Example :-
void main()
{
int b = 5;
auto int a = 5; // Same as above . Auto keyword is default keyword.
printf(" %d, %d ", a,b);
}
Output :-
5,5
Auto keyword is present by default. No matter whether you write it or not. It stores
the value in RAM.
2) static variables in c
static variables are initialised only once in a lifetime of program. That means it gets
initialsed only once when function is called . It's default value is zero.
Example
#include <stdio.h>
void function()
{
static int a = 0; /* This statement gets initialised only once then it is ignored. */
int b = 0;
a++;
Output
b++;
a=1b=1
printf("\na = %d , \nb = %d",a,b);
a=2b=1
} a=3b=1
int main ()
{
function ();
function ();
function ();
return 0; }
3) register
register variables are mostly used in places where we need fast execution .
Because it is stored in register and registers are always fast than RAM. It is mostly
used in incrementing the counter or in loops.
#include <stdio.h>
void main()
{
int b = 5;
register int a = 5;
printf(“%d%d”,a,b);
}
Output
5 5
4) extern : The extern storage class is used to give a reference of a global variable that
is visible to ALL the program files. When you use 'extern', the variable cannot be
initialized however, it points the variable name at a storage location that has been
previously defined.
The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.
Recursion:
In programming terms, a recursive function can be defined as a routine
that calls itself directly or indirectly.
Recursion Function Programs:
1) Factorial
2) Gcd with Lcm
3) Prime number
4) Fibonacci
5) Multiplication
6) Binary to Decimal ( Lab Program 11)
Factorial Program using Recursion
Recursive Solution:
Factorial can be calculated using following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
#include<stdio.h>
int find_factorial(int);
int main() int find_factorial(int n)
{ {
int num, fact; //Factorial of 0 is 1
printf("\nEnter any integer number:"); if(n==0)
scanf("%d",&num); return(1);
#include<stdio.h>
int Fibonacci(int);
int Fibonacci(int n)
int main()
{
{
if ( n == 0 )
int n, i = 0, c;
scanf("%d",&n); return 0;
printf("Fibonacci series\n"); else if ( n == 1 )
for ( c = 1 ; c <= n ; c++ ) return 1;
{ else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
printf("%d\n", Fibonacci(i));
}
i++;
}
return 0;
}
Finding Prime number using recursive function
int primeno(int num, int i)
#include <stdio.h>
int primeno(int, int); {
int main() if (i == 1)
{ {
int num, check; return 1;
printf("Enter a number: "); }
scanf("%d", &num); else
check = primeno(num, num / 2); {
if (check == 1)
if (num % i == 0)
{
printf("%d is a prime number\n", num);
{
} return 0;
else }
{ else
printf("%d is not a prime number\n", num); {
} return primeno(num, i - 1);
return 0; }
} }
}
Write a C recursive function for multiplying two integers where a
function call is passed with two integers m and n.
Array initialization
data_type arr_name *arr_size+=(value1, value2,value3,….);
Syntax:
datatype array[size]; // size= max count of elements that can be stored inside array.
int main()
{
int arr[5]; arr[0] arr[1] arr[2] arr[3] arr[4]
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
return 0;
}
// Program to take 5 values from the user and store them in an
raryint the elements stored in the array
//rP
#include <stdio.h>
2 4 3 5 7
int main()
{ Values[0] Values[1] Values[2] Values[3] Values[4]
int values[10];
printf("Enter 5 integers: "); // 2 4 3 5 7
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]); // Reading 2 4 3 5 7
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
}
return 0;
}
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() { Output
int marks[10], i, n, sum = 0, average;
Enter number1= 2
printf("Enter number of elements: ");
Enter number2= 3
scanf("%d", &n); // n=4 Enter number3= 1
Enter number4= 0
for(i=0; i < n; ++i) // n=4, i= 0 to 3 Average=1
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]); // reading 2 3 1 0
return 0;
}
Read n number of values in an array and display it in reverse order
#include <stdio.h>
void main()
{
int i, n, a[100];
for(i=0;i<n;++i)
{
scanf("%d",&a[i]); // 3 2 5
}
for(int i = n-1; i >=0; --i)
{
printf("%d\n", a[i]); // 5 2 3
}
Two Dimensional Array ( 2-D Array)
The two dimensional (2D) array in C programming is also known as
matrix. A matrix can be represented as a table of rows and columns.
Syntax:
Row major order:
datatype array_ name [row-size] [column-size];
Col major order:
datatype array_ name [column-size] [row-size];
data_type array_name[size1][size2];
We have two different methods in initializing the values in C. The methods only
differ syntactically.
Generally, the first method of initialization is preferred as we can clearly understand and
visualize the rows and columns of 2-D Arrays in C.
An array can be initialized in two ways, which are as follows −
Following is the C Program for compile time initialization ( Read & Display array elements) −
#include<stdio.h>
main ( ){
int a[3][3] = {10,20,30,40,50,60,70,80,90};
int i,j; // i= row position, j= col position
printf ("elements of the array are"); Output
for ( i=0; i<3; i++) // based on row position The output is stated below −
{
for (j=0;j<3; j++) // based on col position elements of the array are:
{ 10 20 30
printf("%d \t", a[i][j]); 40 50 60
} 70 80 90
printf("\n");
}
}
Following is the C program for runtime initialization(Read & Display Array Elements) −
#include<stdio.h>
main ( ){
int a[3][3] ,i, j;
printf ("enter elements of array");
for ( i=0; i<3; i++){
for (j=0;j<3; j++){ Output
scanf("%d", &a[i] [j] ); The output is stated below −
}
} Enter elements of array :
printf("elements of the array are"); 123456789
for ( i=0; i<3; i++){ Elements of the array are
for (j=0;j<3; j++){ 123
printf("%d\t", a[i] [j] ); 456
} 789
printf("\n");
}
}
C program to calculate sum and product of all elements in an array using run time
compilation
#include<stdio.h>
void main(){
//Declaring the array - run time//
int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
//Reading elements into the array's A and B using for loop//
printf("Enter elements into the array A: \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("A[%d][%d] :",i,j); printf("Enter elements into the array B: \n");
scanf("%d",&A[i][j]); for(i=0;i<2;i++){
} for(j=0;j<3;j++){
printf("\n"); printf("B[%d][%d] :",i,j);
} scanf("%d",&B[i][j]);
}
printf("\n");
}
Output:
//Calculating sum and printing output// Enter elements into the array A:
printf("Sum array is : \n"); A[0][0] :2
for(i=0;i<2;i++){ A[0][1] :3
for(j=0;j<3;j++){ A[0][2] :1
sum[i][j]=A[i][j]+B[i][j]; A[1][0] :2
printf("%d\t",sum[i][j]); A[1][1] :4
} A[1][2] :5
Enter elements into the array B:
printf("\n");
B[0][0] :1
}
B[0][1] :2
B[0][2] :3
//Calculating product and printing output// B[1][0] :5
printf("Product array is : \n"); B[1][1] :6
for(i=0;i<2;i++){ B[1][2] :7
for(j=0;j<3;j++){ Sum array is :
product[i][j]=A[i][j]*B[i][j]; 354
printf("%d\t",product[i][j]); 7 10 12
Product array is :
}
263
printf("\n"); 10 24 35
}
}
Multi Dimensional Array ( 2-D / 3-D
Array)
The general form of declaring N-dimensional arrays:
Method 1:
Better Method:
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Accessing elements in Three-Dimensional Arrays:
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12