Module-2
Arrays and Functions
Arrays and Functions: Array – Definition, Initialization, Declaration, One-dimensional
arrays, String operations.
Functions: Definition, Built-in and User-defined functions.
Array:
Array is a linear data structure that is a collection of similar data types. Arrays are stored in
contiguous memory locations. It is a static data structure with a fixed size. It combines data of
similar types.
Declaring Arrays
Syntax:
type arrayName [ arraySize ];
This is called a single-dimensional array.
Ex:
• int num[35]; /* An integer array of 35 elements */
• char name[10]; /* An array of characters for 10 elements */
Initialization an array
However you can also initialize the array during declaration like this:
• int arr[5] = {1, 2, 3, 4 ,5};
OR
• int arr[] = {1, 2, 3, 4, 5};
Example:
• int mark[5] = {19, 10, 8, 17, 9};
Types of arrays
One-dimensional Array
Two-dimensional Array
Three-dimensional Array
Two dimensional and three dimensional arrays are also called multi-dimensional arrays.
One-dimensional Array
In C programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called as one-
dimensional arrays, Linear Arrays or simply 1-D Arrays.
Declaration of Single Dimensional Array
Syntax for declaring a single dimensional array
datatype arrayName [ size ] ;
Ex:
int rollNumbers [60] ;
Examples of Array Program
Ex:1
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
printf("%d\t",arr[i]);
OUTPUT
234
Ex:2
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() {
int marks[10], i, n, sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i) {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
// explicitly convert sum to double
// then calculate average
average = (double) sum / n;
printf("Average = %.2lf", average);
return 0;
Output:
Enter number of elements: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39.60
Two dimensional Arrays
C language supports two dimensional arrays also. The simplest form of a multidimensional array
is the two-dimensional array. Both the row's and column's index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
Example int a[3][4];
Three-dimensional array:
In three-dimensional array, there will be three dimensions. The array face [5] [10] [15] can hold
750 elements (5 * 10 * 15).
/ A sample program for Array Declaration
#include <stdio.h>
int main()
int one_dim [10]; # declaration of 1D array
int two_dim [2][2]; #declaration of 2D array
int three_dim [2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
}; #declaration of 3D array. Here the elements are also defined.return 0;
}
Array Operation:
Various operations that can be performed on arrays.
Traverse − Print all the elements in the array one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element in the array using the given index or the value.
Update − Updates an element at the given index.
Applications of Array Data Structure:
Below are some applications of arrays.
Arrays are used to implement data structures like a stack, queue, etc.
Arrays are used for matrices and other mathematical implementations.
Arrays are used in lookup tables in computers.
Arrays can be used for CPU scheduling.
Advantages of array data structure:
Arrays store multiple data of similar types with the same name.
It allows random access to elements.
As the array is of fixed size and stored in contiguous memory locations there is no memory
shortage or overflow.
It is helpful to store any type of data with a fixed size.
Since the elements in the array are stored at contiguous memory locations it is easy to
iterate in this data structure and unit time is required to access an element if the index is
known.
Disadvantages of array data structure:
The size of the array should be known in advance.
The array is a static data structure with a fixed size so, the size of the array cannot be
modified further and hence no modification can be done during runtime.
Insertion and deletion operations are costly in arrays as elements are stored in contiguous
memory.
If the size of the declared array is more than the required size then, it can lead to memory
wastage.
String:
String is an array of characters.
The difference between a character array and a string is the string is terminated with a special
character ‘\0’
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in
C.
Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax
for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
EXAMPLE FOR C STRING:
• char string[5] = {‘I’,’S’,’E’, ‘\0’};
or
• char string[5] = “ISE”;
(or)
• char string [] = “ISE”;
Example 1:
#include <stdio.h>
int main ()
char string[20] = “ISE";
printf("The string is : %s \n", string );
return 0;}
Example 2:
#include <stdio.h>
int main()
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
String Operations:
String functions Description
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl <
strcmp ( )
str2. Returns >0 if str1 > str2
strlen( ) Function :
strlen( ) function is used to find the length of a character string.
Example:
int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable n.
#include <stdio.h>
#include <string.h>
int main ()
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12]; int len ; /* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
OUTPUT
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Functions:
In C, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the C program.
The function is also known as procedure or subroutine
Need Functions in C Programming:
We need functions in C programming and even in other programming languages due to the
numerous advantages they provide to the developer. Some of the key benefits of using functions
are:
Enables reusability and reduces redundancy
Makes a code modular
Provides abstraction functionality
The program becomes easy to understand and manage
Breaks an extensive program into smaller and simpler pieces
Advantage of functions in C:
• By using functions, we can avoid rewriting same logic/code again and again in a
program.
• We can call C functions any number of times in a program and from any place in a
program.
• We can track a large C program easily when it is divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C program.
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c program to tell the
compiler about the function name, function parameters, and return type.
o 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.
o 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.
Syntax
• Function declaration
return_type function_name (argument list);
• Function call
function_name (argument_list)
• Function definition
return_type function_name (argument list)
function body;
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.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
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.
Function Body − The function body contains a collection of statements that define what
the function does.
Ex:
#include <stdio.h>
// Function declaration
int max_Num(int i, int j){
// Function definition
if (i > j)
return i;
else
return j;
}
// The main function.
int main(void){
int x = 15, y = 20;
// Calling the function to find the greater number among the two
int m = max_Num(x, y);
printf("The bigger number is %d", m);
return 0;
}
Output:
The bigger number is:20
Types of Functions
There are two types of functions in C programming:
• Built in or Library Functions
• User-defined functions:
Built in or Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts().
Example
int main() {
printf("Hello World!");
return 0;
User-defined functions:
User defined functions are the functions which are created by the C programmer, so that
he/she can use it many times.
Different aspects of function calling:
• A function may or may not accept any argument. It may or may not return any value.
Based on these facts,
There are four different aspects of function calls.
• function without arguments and without return value
• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value
Example for Function without argument and return value
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(“ECE");
}
OUTPUT: Hello ECE
Example for Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers
10 24
The sum is 34
Example for Function with argument and without return value:
#include<stdio.h>
void 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);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10 24
The sum is 34
Example for Function with argument and with return value:
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by the
designers of compilers. All C standard library functions are defined inside the different header
files saved with the extension .h.
We need to include these header files in our program to make use of the library functions defined
in such header files.
For example, To use the library functions such as printf/scanf we need to include stdio.h in our
program which is a header file that contains all the library functions regarding standard
input/output.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.