Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

FUNCTIONS AND

ARRAYS
UNIT II
CONTENTS

¡ Functions Introduction, User defined function, Function prototype,


Function Definition and Function Call, Storage classes, Recursion.
Arrays: Defining an array, processing an array, one dimensional
arrays, two dimensional arrays. Passing array as an argument to
function. Sorting: Bubble Sort, Insertion Sort, selection sort.
Searching: Linear and binary search.
FUNCTIONS INTRODUCTION
¡ A function is a group of statements that together perform a task. Every C program has
at least one function, which is main().
¡ Defining a Function: The general form of a function definition in C programming
language is as follows −
return_type function_name( parameter list )
{
body of the function
}
CONTINUED…….
¡ A function definition in C programming consists of a function header and a function body. Here are all the
parts of a function −
v 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.
v Function Name − This is the actual name of the function. The function name and the parameter list together
constitute the function signature.
v Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. 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.
v Function Body − The function body contains a collection of statements that define what the function does.

v A function is a block of code that performs a specific task.


DIFFERENCE BETWEEN PARAMETERS AND ARGUMENTS
Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the
function.
Arguments
¡ When a function is called, the values that are passed during the call are called as arguments.
¡ They are also called Actual Parameters
int num = 20;
Call(num)// num is argument
Parameters
¡ The values which are defined at the time of the function prototype or definition of the function are called as
parameters.
¡ They are also called Formal Parameters
int Call(int rnum)
{
printf("the num is %d", rnum);
}
1. WITHOUT ARGUMENTS PASSED AND WITHOUT RETURN VALUE
¡ The empty parentheses in (); statement inside the main() function indicates that no argument is passed to the function.
¡ The return type of the function is void. Hence, no value is returned from the function.
Example:
#include<stdio.h>
void greet();//Function declaration
int main()
{
greet();
return 0;
}
void greet()
{
printf("Welcome");
}
2. WITHOUT ARGUMENTS PASSED BUT WITH RETURN VALUE
¡ The empty parentheses in the (); statement indicates that no argument is passed to the function.
¡ The return type of the function is int. Hence, value is returned from the function.
Example:
#include<stdio.h>
int sum();//Function declaration
int main()
{
printf("The sum is %d",sum());
return 0;
}
int sum()
{
int a=10,b=20;
return a+b;
}
3. WITH ARGUMENT PASSED BUT WITHOUT RETURN VALUE
¡ The parentheses with parameters in the (); statement indicates that argument is passed to the function.
¡ The return type of the function is void. Hence, no value is returned from the function.
Example:
#include<stdio.h>
void sum(int a,int b);//Function declaration
int main()
{
int a=10,b=20;
sum(a,b);
return 0;
}
void sum(int a,int b)
{
printf("The sum is %d",a+b);
}
4. WITH ARGUMENT PASSED AND WITH A RETURN VALUE
¡ The parentheses with parameters in the (); statement indicates that argument is passed to the function.
¡ The return type of the function is int. Hence, value is returned from the function.
Example:
#include<stdio.h>
int sum(int a,int b);//Function declaration
int main()
{
int a=10,b=20;
printf("The sum is %d",sum());
return 0;
}
int sum(int a,int b)
{
return a+b;
}
EXAMPLE PROGRAMS USING FUNCTIONS
1.Swapping of three numbers.
2.To find even or odd.
3.To find biggest among the three numbers.
4.Sum and product of n natural numbers.
5.factorial of a number.
6.Arithmetic operation using switch.
7.Prime or not.
8. To print Fibonacci series.
9.To print prime number series.
10. Program to find Armstrong, perfect, strong and palindrome or not using switch.
INCREMENT/DECREMENT OPERATORS
Increment/Decrement operators are of two types:
1. Prefix increment/decrement operator.(initially assigns the increment/decrement value)
Example: ++X, --Y
1. Postfix increment/decrement operator.(First assign the actual value and then increment/decrement)
Example: X++,Y—
Solve:
1.x=5,y=8,
z=++x + y++.,z=?
2.a=10,b=20,c=1,
c += a++ * 5 - --b,c=?
3.a=1,b=1,d=1,
++a + ++a + a++, a++ + ++b, ++d + d++ + a++
(what are the final values of a,b,d)?
STORAGE CLASSES
¡ A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program. They precede the type that they modify. We have four different
storage classes in a C program −
1. auto
2. register
3. static
4. extern
THE AUTO STORAGE CLASS
¡ The auto storage class is the default storage class for all local variables.
Int main()
{
int mount;
auto int month;
}
¡ The example above defines two variables within the same storage class. 'auto' can
only be used within functions, i.e., local variables.
THE REGISTER STORAGE CLASS
¡ The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location).
Int main()
{
register int miles;
}
¡ The register should only be used for variables that require quick access such as counters. It
should also be noted that defining 'register' does not mean that the variable will be stored in
a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.
THE STATIC STORAGE CLASS
¡ The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows them
to maintain their values between function calls.
¡ The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
¡ In C programming, when static is used on a global variable, it causes only one copy of
that member to be shared by all the objects of its class.
EXAMPLE
#include <stdio.h>
void fun();
static int count = 5; /* global variable */
int main()
{
int i;
for(i=count;i>0;i--)
{
func();
}

return 0;
}
void func( void )
{
static int i = 5;
i++;
printf("i is %d and count is %d\n", i, count);
}
THE EXTERN STORAGE CLASS

¡ 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.
¡ When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another file.
¡ The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions.
¡ External variables are also known as global variables. These variables are defined outside the function.
These variables are available globally throughout the function execution. The value of global variables can
be modified by the functions. “extern” keyword is used to declare and define the external variables.
EXAMPLE
First File: main.c
Second File: support.c
#include <stdio.h>
#include “support.c” #include <stdio.h>

int count ; extern int count;


extern void fun();
void fun()
main()
{
{
count = 5; printf("count is %d\n", count);
fun(); }
}
RECURSION
Recursion is the process of repeating items in a self-
similar way. In programming languages, if a
program allows you to call a function inside the
same function, then it is called a recursive call of the
function.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
EXAMPLE PROGRAMS

1. Write a program in C to print first 50 natural numbers using recursion.


2. Sum of Natural Numbers Using Recursion
3. Write a program in C to print even or odd numbers in given range using recursion.
4. Write a program in C to calculate the power of any number using recursion.
5. Program to find factorial of a number using recursion.
6. Program to print Fibonacci series using recursion.
7. Write a program in C to count the digits of a given number using recursion.
8. Write a program in C to find the sum and product of digits of a number using recursion.
9. Write a program in C to check a number is a prime number or not using recursion.
10. Write a program in C to print numbers in reverse order.
LAB SYLLABUS PROGRAMS

a) Write a C program to find sum of digits, Decimal to Binary conversion, reversal of numbers using
functions.
b) Write a C program to find Factorial, Greatest Common Divisor, and Fibonacci using recursion
RETURN A FLOAT VALUE
#include<stdio.h>
float sum(float a,float b);
int main()
{
float a=1.2,b=1.3;
printf("the sum is %.2f",sum(a,b));
return 0;
}
float sum(float a,float b)
{
return a+b;
}
RETURN A CHARACTER

#include<stdio.h>
char greet(char c );
int main()
{
char c="W";
printf("the string is %c",greet(c));
return 0;
}
const greet(char c)
{
return c;
}
RETURN A STRING
#include<stdio.h>
const char* greet(char c[10]);
int main()
{
char c[10]="Welcome";
printf("the string is %s",greet(c));
return 0;
}
const char* greet(char c[10])
{
return c;
}
PART 2
ARRAYS
DEFINING AN ARRAY
PROCESSING AN ARRAY
ONE DIMENSIONAL ARRAYS
TWO DIMENSIONAL ARRAYS
PASSING ARRAY AS AN ARGUMENT TO FUNCTION
DEFINING AN ARRAY
¡ Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
¡ All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
DECLARING ARRAYS

How to declare an array?


¡ dataType arrayName[arraySize];

For example,
¡ float mark[5];

Access Array Elements


¡ You can access elements of an array by indices.

¡ Suppose you declared an array mark as above. The first element is mark[0], the second element
is mark[1] and so on.
HOW TO INITIALIZE AN ARRAY?(ONE DIMENSIONAL ARRAYS)

¡ It is possible to initialize an array during declaration.


¡ For example,
int mark[5] = {19, 10, 8, 17, 9};
¡ You can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
¡ Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
¡ User input:
int values[5];
EXAMPLE PROGRAMS
1. Program to take 5 values from the user and store them in an array and Print the elements stored in the
array
2. Program to find the average of n numbers using arrays.
3. Program to find the multiplication of numbers in arrays.
4. Write a program in C to copy the elements of one array into another array.
5. Write a program in C to separate odd and even integers in separate arrays.
6. Write a program in C to find the maximum and minimum element in an array.
7. Write a program in C to print and count a total number of duplicate elements in an array.
8. Write a program in C to print all unique elements in an array.
9. Write a program in C to count the frequency of each element of an array.
10. Write a program in C to sort elements of the array in ascending and descending order.
11. Write a program in C to delete an element at desired position from an array.

12. Write a program in C to find the second largest and second smallest element in an array.
MULTI DIMENSIONAL ARRAYS(TWO DIMENSIONAL ARRAYS)

¡ In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
¡ int x[3][4];
¡ Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think
the array as a table with 3 rows and each row has 4 columns.
¡
INITIALIZATION OF A 2D ARRAY

Different ways to initialize two-dimensional array


¡ int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
¡ int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
¡ int c[2][3] = {1, 3, 0, -1, 5, 9};
¡ Int c[2][3]
EXAMPLE PROGRAMS

1. Write a program in C for a 2D array of size 3x3 and print the matrix.
2. Write a program in C for addition of two Matrices of same size.
3. Write a program in C for subtraction of two Matrices.
4. Write a program in C for multiplication of two square Matrices.
5. Write a program in C to find transpose of a given matrix.
6. Write a program in C to find sum of rows and columns of a Matrix.
7. Write a program in C to accept two matrices and check whether they are equal.
LAB SYLLABUS PROGRAMS ON ARRAYS
Your program should take as input: dimension of a square matrix N, two
matrices of size N x N with integer values, and one operator symbol (+, -
,*). It must perform the corresponding operation given below;
¡ Matrix Addition b) Matrix Subtraction c) Matrix Multiplication
PASSING ARRAY AS AN ARGUMENT TO FUNCTION

Method 1:
¡ Formal parameters as a sized array −
void myFunction(int param[10])
{...}
Method 2:
¡ Formal parameters as an unsized array −
void myFunction(int param[])
{...}
EXAMPLE
#include<stdio.h>
int sum(int a[],int n);
int main()
{ int n,i;
printf("enter the size");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{printf("enter the value");
scanf("%d",&a[i]);}
sum(a,n);
return 0;}
int sum(int a[],int n)
{ int i;
for(i=0;i<n;i++){
printf("%d\n",a[i]);}
}
SORTING TECHNIQUES

1. Bubble Sort
2. Insertion Sort
3. selection sort
BUBBLE SORT
¡ Bubble sort is the simplest sorting algorithm. In this technique we follow given step to short
given elements in increasing order.
Steps to Sort data
1. First compare First (previous) element with its next elements.
2. If next element is grater than previous element just ignore it.
3. If next element is smaller than previous element then interchange their position.

Advantage of Bubble short


¡ It is very simple and easy method to short elements.
Dis-Advantage of Bubble short
¡ It is time comsuming and slow process to short elements.
INSERTION SORT

¡ Insertion Sort is a simplest data Sorting


algorithm which sorts the array elements
by shifting elements one by one and
inserting each element into its proper
position. This technique is also used for
sort array elements.
SELECTION SORT
¡ Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that
element at the beginning of the unsorted list.
¡ Working of Selection Sort
Ø Set the first element as minimum
Ø Compare minimum with the second element. If the second element is smaller than minimum, assign the second element
as minimum.

Compare minimum with the third element. Again, if the third element is smaller, then assign minimum to the third element
otherwise do nothing. The process goes on until the last element.
Ø After each iteration, minimum is placed in the front of the unsorted list.
For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all the elements are placed at
their correct positions.
LAB PROGRAMS

Implement the following sorting techniques. Bubble sort b)


Insertion sort c) Selection sort.
Refer: https://www.programiz.com/dsa/selection
SEARCHING TECHNIQUES

¡Linear search
¡Binary search.
LINEAR SEARCH

Linear search is also called as sequential search. Linear


search is a method for finding a particular value in a list. In
this searching technique you need to check every elements
one by one until desired element found.
BINARY SEARCH

¡ This searching technique is applicable only for sorted array, but this searching technique is faster than linear
search.
¡ Steps for binary search

¡ You need to first sort elements of array if it is not in sorted order, because binary search is only application
on sorted element.
STEPS

¡ First find the middle element of the array.


¡ Compare the middle element with the item. After this step there are three cases;
¡ 1. If middle element is a desired item then search is successful
¡ 2. If middle element is less than desired item then search only the first half of the
array.
¡ 3.If middle element is grater than the desired item search in the second half of the
array.
¡ 4. Repeat same steps until element is found.
LAB PROGRAMS

Implement the following searching techniques.


Linear Search b) Binary Search
END OF UNIT 2

Kindly refer the programs updated in moodle and also solved


examples in class.

You might also like