Module 4

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

MODULE 4

4.1 Array
An array is a fixed-size sequenced collection of elements of the same data type. It is simply a
grouping of like-type data. An array can be used to represent a list of numbers, or a list of names.
An array is a collective name given to a group of homogeneous elements (same data type). These
similar quantities could be percentage marks of 100 students, or salaries of 300 employees or ages
of 25 students.
Declaration of an Array
Arrays must be declared before they can be used in the program.
Standard array declaration is as
type variable_name [size];
The type specifies the type of the elements that will be contained in the array, such as int, float or
char and the size indicates the maximum number of elements that can be stored inside the array. In
C Language, an array starts at position 0.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
eg: int Age[5];
Age[0]
Age[1]
Age[2]
Age[3]
Age[4]

The values to the array elements can be assigned as follows


Age[0] =35;
Age[1] =40;
Age[2] =20;
Age[3] =55;
Age[4] =25;

The value will be stored in array Age as shown below.


Age[0] 35
Age[1] 40
Age[2] 20
Age[3] 55
Age[4] 25

Character array declaration and initialization

char name[10];
Here we declare the name as a character array (string) variable that can hold a maximum of 10
characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”
Array will be like this..
‘W’

‘E’

‘L’

‘L’

‘’

‘D’

‘O’

‘N’

‘E’

‘\0’

When compiler sees the character string, it terminates with an additional null character, thus the
element name[10] holds the null character ‘\0’ . When declaring character arrays, we must allow
one extra element space for the null terminator.
What is Contiguous Memory?

1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.

Array Terminologies:

Size: Number of elements or capacity to store elements in an array. It is always mentioned in


square brackets [ ].

Type: Refers to data type. It decides which type of element is stored in the array. It is also instructing
the compiler to reserve memory according to the data type.

Base: The address of the first element is a base address. The array name itself stores address of the
first element.

Index: The array name is used to refer to the array element. For example num[x], num is array and
x is index. The value of x begins from 0.The index value is always an integer value.

Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.

Word: It indicates the space required for an element.

Characteristics of an array:

1. The declaration int a[5] is nothing but creation of five variables of integer types in memory
instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one another
with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array
variable of its type.
6. Array elements are stored in contiguous memory locations.

Types of Array
1. Single Dimensional Array / One Dimensional Array

2. Multi-Dimensional Array
Single / One Dimensional Array:

• Single or One Dimensional array is used to represent and store data in a linear form.
• Array having only one subscript variable is called One-Dimensional array.
• It is also called as Single Dimensional Array or Linear Array.
Single Dimensional Array Declaration and initialization:

Syntax for declaration:

<data type> <array name> [size];

Examples for declaration

int iarr[3];

char carr[20];

float farr[3];

Syntax for initialization:

<data type> <array name> [size] = {val1, val2, …, valn};

Examples for initialization:

int iarr[3] = {2, 3, 4};

char carr[20] = “program”;

float farr[3] = {12.5, 13.5, 14.5};

Different Methods of Initializing 1-D Array

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set of
values to array element before executing program. i.e. at compilation time.
Ways of Array Initializing 1-D Array:

1. Size is Specified Directly

2. Size is Specified Indirectly

Method 1: Array Size Specified Directly

In this method, we try to specify the Array Size directly.

int num [5] = {2,8,7,6,0};

In the above example we have specified the size of array as 5 directly in the initialization statement.
Compiler will assign the set of values to particular element of the array.

num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;

Method 2: Size Specified Indirectly

int num[ ] = {2,8,7,6,0};

Explanation:

1. Compiler counts the number of elements written inside pair of braces and determines the size
of an array.
2. After counting the number of elements inside the braces, the size of array is considered as 5
during complete execution.
3. This type of Initialization Scheme is also called as “Compile Time Initialization”.
Example Program

#include <stdio.h>

void main()

int num[] = {2,8,7,6,0};

int i;

for (i=0;i<5;i++)

printf(“\n Array Element num [%d] = %d”,i, num[i]);

getch();

Output:

Array Element num[0] = 2

Array Element num[1] = 8

Array Element num[2] = 7

Array Element num[3] = 6

Array Element num[4] = 0

Accessing Array

1. We all know that array elements are randomly accessed using the subscript variable.

2. Array can be accessed using array-name and subscript variable written inside pair of square
brackets [ ]. Consider the below example of an array

20 30 10 40 70

a[0] a[1] a[2] a[3] a[4]

In this example we will be accessing array like this

a[3] = Forth Element of Array

a[4] = Fifth Element of Array


Whereas elements are assigned to an array using below way

a [0] = 20; a[1] = 30; a[2] = 10; a[3] = 40; a[4] = 70;

READING AN AARAY USING scanf()

void main()

int a[5];
clrscr();
printf(“Enter a number\n”);

scanf(“%d”,&a[0]);
}
We can read number of elements in single statements by using for loop.
void main()

int i,a[5];

clrscr();

printf(“Enter five numbers\n”);


for(i=0;i<5;i++)
{

scanf(“%d”,&a[i]);
}

Operations with One Dimensional Array


1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific elements in an
array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending order.
Example Programs:
C Program for deletion of an element from the specified location from an Array
#include<stdio.h>
void main()
{
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++)

{
scanf("%d", &arr[i]);
}
//Read the location
printf("\nLocation of the element to be deleted :");
scanf("%d", &loc);
/* loop for the deletion */
while (loc < num)

{
arr[loc - 1] = arr[loc];
loc++;

num--; // No of elements reduced by 1

//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
getch();

}
Output:

Enter no of elements: 5
Enter 5 elements: 3 4 1 7 8
Location of the element to be deleted: 3

3 4 7 8

C Program to insert an element in an array


#include<stdio.h>
int main()

int arr[30], element, num, i, location;


printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++)

scanf("%d", &arr[i]);
}

printf("\nEnter the element to be inserted:");


scanf("%d", &element);
printf("\nEnter the location");

scanf("%d", &location);

//Create space at the specified location


for (i = num; i >= location; i--)
{

arr[i] = arr[i - 1];

num++;
arr[location - 1] = element;
//Print out the result of insertion
for (i = 0; i < num; i++)
printf("n %d", arr[i]);

return (0);
}

Output:
Enter no of elements: 5
12345
Enter the element to be inserted: 6

Enter the location: 2


162345

C Program to search an element in an array


#include<stdio.h>
int main()
{

int a[30], ele, num, i;

printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++)

scanf("%d", &a[i]);
}

//Read the element to be searched


printf("\nEnter the element to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i])
{
i++;

//If i < num then Match found


if (i < num)
{

printf("Number found at the location = %d", i + 1);


}

else

printf("Number not found");


}

getch();

Output:

Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4
C program to merge two arrays in C Programming
#include<stdio.h>
int main()

int arr1[30], arr2[30], res[60];


int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st array:");

scanf("%d", &n1);
for (i = 0; i < n1; i++)

scanf("%d", &arr1[i]);

printf("\nEnter no of elements in 2nd array:");

scanf("%d", &n2);

for (i = 0; i < n2; i++)


{
scanf("%d", &arr2[i]); }
i = 0;
j = 0;

k = 0;

// Merging starts
while (i < n1 && j < n2)
{

if (arr1[i] <= arr2[j])

res[k] = arr1[i];
i++;
k++;

else
{

res[k] = arr2[j];
k++;

j++;
}

/*Some elements in array 'arr1' are still remaining where as the array 'arr2' is exhausted*/

while (i < n1)


{

res[k] = arr1[i];
i++;
k++;
}

/*Some elements in array 'arr2' are still remaining where as the array 'arr1' is exhausted */
while (j < n2)

res[k] = arr2[j];
k++;
j++;

//Displaying elements of array 'res'


printf("\nMerged array is:");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
return (0);

Output

Enter no of elements in 1st array: 4


11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80
Merged array is: 10 11 22 33 40 44 80

4.3 Multi Dimensional Array and Operations:

1. Array having more than one subscript variable is called Multi-Dimensional array.

2. Two Dimensional Array (with two dimensions) is also called as Matrix.

Syntax: <data type> <array name> [row subscript] [column subscript];

Example:

Two Dimensional Arrays Declaration:

char name[50][20];
Initialization:
int a[3][3] = { {1, 2, 3}, { 4, 5, 6},{ 7,8, 9} };

Here
a[0][0]=1; a[0][1]=2; a[0][2]=3;

a[1][0]=4; a[1][1]=5; a[1][2]=6;


a[2][0]=7; a[2][1]=8; a[2][2]=9;

Two Dimensional Arrays:

• 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.
Declaration and use of 2D Arrays:
int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++)

printf("%d",a[i][j]);
}

Example Program: Accept & Print 2×2 Matrix from user


#include<stdio.h>
void main()

int i, j, a[3][3];
for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)


{

printf("\nEnter the a[%d][%d] = ", i, j);


scanf("%d", &a[i][j]);
}

//Print array elements


for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf("%d\t", a[i][j]);

printf("\n");
}
getch();

Example programs for practice:


C Program for addition of two matrices

C Program to find inverse of 3 X 3 Matrix

C Program to multiply two 3 X 3 Matrices

C Program to check whether matrix is magic square or not?

STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with \0. The
compiler puts \0 at the end of string to specify the end of the string. To get a value of string variable
we can use the two different types of formats.

• Using scanf() function as: scanf(“%s”, string variable);


• Using gets() function as : gets(string variable);
STRING HANDLING FUNCTIONS

C library supports a large number of string handling functions. Those functions are stored under the
header file string.h in the program.

Let us see about some of the string handling functions.

I. strlen() function
strlen() is used to return the length of the string , that means counts the number of

characters present in a string.

Syntax
integer variable = strlen (string variable);
Example:
void main()
{
char str[20];
int strlength;
clrscr();
printf(“Enter String:”);
gets(str);
strlength=strlen(str);
printf(“Given String Length Is: %d", strlength);
getch();
}
Output:

Enter String
Welcome

Given String Length is:7

II. strcat() function


The strcat() is used to concatenate two strings. The second string will be appended to the end of the
first string. This process is called concatenation.

Syntax

strcat (StringVariable1, StringVariable 2);

Example:

void main()
{
char str1[20],str2[20];
clrscr();

printf(“Enter First String:”);


scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);

printf(“Concatenation String is:%s\n”, strcat(str1,str2));


getch();

}
Output:

Enter First String


Good

Enter Second String


Morning

Concatenation String is:

GoodMorning

III. strcmp() function

strcmp() function is used to compare two strings. strcmp() function does a case sensitive comparison
between two strings. The two strings are compared character by character until there is a mismatch
or end of one of the strings is reached (whichever occurs first). If the two strings are identical,
strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the ASCII
values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
res = strcmp(str1,str2);
if(res==0)
printf(“strings are equal”);
else
printf(“strings are not equal”);
getch();
}
Output:
Enter First String
Good
Enter Second String
Good

Strings are equal

Note:

strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not case
sensitive.
IV. strcpy() function:
strcpy() function is used to copy one string to another. strcpy() function copy the contents of second
string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(“Enter First String:\n”);
scanf(“%s”,str1);
printf(“Enter Second String:\n”);
scanf(“%s”,str2);
strcpy(str1,str2)
printf(“First String is:%s\n”,str1);
printf(“Second String is:%s”,str2);
getch();
}
Output:
Enter First String:
Hello
Enter Second String:
welcome
First String is: welcome
Second String is: welcom
V. strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Lowercase String : %s”, strlwr(str));
getch();
}
Output:
Enter String
WELCOME
Lowercase String : welcome

VI. strrev() function:


strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Reverse String : %s”, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : EMOCLEW

Note:
strupr() function:

strupr() function is used to convert all characters in a given string from


lower case to uppercase letter.

Syntax

strupr(Stringvariable);
Pointers

The pointer in C language is a variable which stores the address of another variable. An

integer variable holds (or you can say stores) an integer value, however an integer pointer holds the

address of an integer variable.

Consider the following example to define a pointer which stores the address of an integer.

int n = 10;

int *p = &n; // pointer declaration and initialization in single line.


n
10
5001

Here value of n=10 and value of p=5001.

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

int *a; //pointer to int

char *c; //pointer to char

By the help of * (indirection operator), we can print the value of pointer variable p

Eg P33:-#include<stdio.h>
int main()

int number=50; int *p;

p=&number; //stores the address of number variable

printf("Address of p variable is %x \n",p); // p contains the address of the number


printf("Value of p variable is %d \n",*p); // *p print the value of pointer variable return
0;

Output

Address of p variable is fff4

Value of p variable is 50
Eg P34:-Write a program to display the value of variable and its location using pointer

void main()

int *v, *p;

clrscr();

p=&v;

printf(“\n address of v=%u”,p);

printf(“\n value of v=%d”,*p);

printf(“\n address of p=%u”,&p);

Output

Address of v=4060

Value of v =10

Address of p=4062
Eg P35:-Write a program to print an element and its address using pointer.

void main ()

int i,*k;
clrscr ();

printf ("Enter a number : ") ;

scanf ("%d", &i) ;

k=&i;
printf (" \nAddress of i is %u", k) ;
printf (" \nValue of i is %d", *k) ;

}
Output

Enter a number: 15

Address of I is 4065

Value of I is 15

Eg P36:- write a program to add two numbers through variables and their pointers.
void main ( )

int a,b,c,d,*ap,*bp;

clrscr();

printf("Enter Two Numbers :");

scanf ("%d %d",&a,&b):

ap=&a;

bp=&b;

c=a+b;

d=*ap+*bp;

printf("\nSum of A & B Using Variable :%d",c);

printf("\nSum of A & B Using Pointers :%d",d);

OUTPUT:

Enter Two Numbers: 8 4

Sum of A & B Using Variable: 12

Sum of A & B Using Pointers: 12

Advantage of pointer

1) Pointer reduces the code and improves the performance; it is used to retrieving strings, trees, etc.

and used with arrays, structures, and functions.


2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many applications of pointers in C language.

1) Dynamic memory allocation

In C language, we can dynamically allocate memory using malloc() and calloc() functions where the

pointer is used.

2) Arrays, Functions, and Structures


Pointers in C language are widely used in arrays, functions, and structures. It reduces the code and

improves the performance.

NULL Pointer

A pointer that is not assigned any value but NULL is known as the NULL pointer. If
you

don't have any address to be specified in the pointer at the time of declaration, you can assign
NULL

value. It will provide a better approach.

int *p=NULL;

P37./*Swapping of two values using pointers*/

#include<stdio.h
> void main()

{
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d
*p2=%d",*p1,*p2); *p1=*p1+*p2;

*p2=*p1-
*p2;
*p1=*p1-
*p2;

printf("\nAfter swap: *p1=%d


*p2=%d",*p1,*p2); getch();

Output

Before swap: *p1=10 *p2=20

After swap: *p1=20 *p2=10

THE void POINTERS


Pointers can also be declared as void types. void pointers cannot be dereferenced
without

explicit type conversion. This is because being void the compiler cannot determine the size of
the

object that the pointer points to. Though void pointer declaration is possible, void
variable's

declaration is not allowed.

A void pointer can point any type of variable with proper type casting. The size of a
void

pointer displayed will be two. When a pointer is declared as void two bytes are allocated to it. Later
using type casting, a number of bytes can be allocated or deallocated. Void variables cannot be

declared because memory is not allocated to them and there is no place to store the address.

WILD POINTERS

Pointers are used to store memory addresses. An improper use of pointer creates many errors

in the program. Hence, pointers should be handled cautiously. When a pointer points to an

unallocated memory location or data value whose memory is de-allocated, such a pointer is called a

wild pointer. That is uninitialized pointers are known as wild pointers. The wild pointer generates

garbage memory location and dependent reference. The pointer becomes wild due to the following
reasons:

• Pointer declared but not initialized


• Pointer alternation

• Accessing the destroyed data

Eg:-Write a program to show the wild pointer and its output.


void main()

int k,*x;

clrscr () ;

for(k=0;k<=3;k++)

printf("%u",x[k]);

OUTPUT:

7272 24 330 30 55 9 2 7 7 53

CONSTANT POINTERS

The address of the constant pointer cannot be modified.

char* const str="Constant";

In the above example, it is not possible to modify the address of the pointer str.

Features of pointers

➢ Pointers provide direct access to memory.

➢ Reduce the storage space and complexity of the program.


➢ Reduces the execution time of the program.

➢ Provides an alternative way to access array elements.

➢ Address of objects can be extracted using pointers.

➢ Pointers help u8s to build complex data structures like linked list, stack, queues.
ARITHMETIC OPERATIONS WITH POINTERS

Arithmetic operations on pointer variables are also possible. Increment, decrement, prefix
and postfix operations can be performed with the pointers, The effects of these operations are shown
in Table.

Initial Address after Required


Data Type Operation
Address Operation Bytes

int i=2 4046 ++ -- 4048 4044 25

char c= ‘x’ 4053 ++ -- 4054 4052 1

float f=2.2 4058 ++ -- 4062 4054 4

long l =2 4060 ++ -- 4064 4056 4


From the table we can observe that, on increment of the pointer variable for integers, the

address incremented by two. i.e. 4046 is the original address and on increment its value will be 4048

because integers require two bytes.

Similarly, characters, floating point numbers and long integers require 1, 4 and 4 bytes,
respectively.

Eg:-P38. Write a program to show the effect of increment and decrement operators used as

prefix and suffix with the pointer variable.

void main ()

int i, *ii;

puts ("Enter Value of i=") ;

scanf ("%d", &i) ;

ii=&i;
clrscr();

printf("Address of i = %u\n", ii);

printf("Address of I = %u\n", ++ii);

printf("Address of i = %u\n", ii++);

printf("Address of i = %u\n", --ii);

printf("Address of i =%u\n", ii--);

printf("Address of i = %u\n", ii);

}
OUTPUT:

Enter Value of i= 8
Address of i = 4060
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4060

Eg:-P39. Write a program to perform different arithmetic operations using pointers.

void main()

int a=25,b=10,*Pi*j;

p=&a; j=&b;
clrscr();

printf("\n Addition a+b = %d", *p+b);

printf("\n Subtraction a-b = %d", *p-b);


printf("\n Product a*b = %d", *p**j);

printf(“\n Division a/b = %d", *p / *j);


printf(“\n a Mod b = %d", *p % *j);

Output

Addition a+ b = 35
Subtraction a-b = 15
Product a*b = 250

Division a/b = 2

a mod b = 5
Basics of a Functions
A function is a block of code that performs a specific task.
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. In other words, we can say that the collection
of functions creates a program. The function is also known as procedure or subroutine in other
programming languages.
Advantage of functions in C

There are the following advantages of C functions.

• 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 an overhead in a C program.

Function Aspects

There are three aspects of a C function.

Function declaration

All functions in a c program must be declared, before they are invoked. A function declaration (also
known as function prototype) consists of four parts.
• Function type (return type).
• Function name.
• Parameter list.
• Terminating semicolon.
The general format of function declaration is:

Function-type function-name (parameter list);


In function declaration:
• The parameter list must be separated by commas.
• The parameter names do not need to be the same in the prototype declaration and the
function definition.
• Use of parameter names in the declaration is optional.
• If the function has no formal parameters, the list is written as (void)
• The return type is optional, when the function returns int type data.
• The return type must be void if no value is returned.
Function definition
Function definition, also known as function implementation includes the following elements;

• Function name.
• Function type.
• List of parameters
• Local variable declaration.
• Function statements; and
• A return statement.
The general format of function definition is:

function-type function-name (parameter list) /* function header*/


{
Local variable declaration; /*
Executable statement1;
………………………
function body
Executable statement n;
Return statement;

Function call

A function can be called by simply using the function name followed by a list of parameters (or
arguments), if any, enclosed in parentheses and separated by commas. If the function call does not
require any arguments, an empty pair of parentheses must follow the name of the function. The
function call may be a part of a simple expression (such as an assignment statement), or it may be
one of the operands within a more complex expression. The arguments appearing in the function
call are referred to as actual parameters.

The general format of function call is:


function name ( actual parameters );
variable = function name (actual parameters);

Function Aspects Syntax

Return_type function_name(argument list);


Function Declaration

Function call Function_name(argument_list);

Return_type function_name(argument list)


Function Definition {
Function body;
}

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...)


{
// Body of the function
}
Types of Functions

Functions

Library Functions User defined Functions

There are two types of functions in C programming:

1.Library functions:

Library functions are built-in functions in Library functions are the functions which are
declared in the C header files (stdio.h) such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

2. 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. It reduces the complexity of a big program and optimizes the code.

Return Value

C function may or may not return a value from the function. If you don't have to return any value
from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the
function.

Example without return value:

void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

int get()
{
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to return
floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.

float get()
{
return 10.2;
}
Now, you need to call the function, to get the value of the function.

4.3 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 without return value

Example
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(" C programming");
}
Output
Hello C programming

Example

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers

10
20
The sum is 30
Example for Function without argument and with return value
Example
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
getch();
}
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
20
The sum is 30

Example
program to calculate the area of the square

#include<stdio.h>
float square();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
getch();
}
float square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f”,&side);
return side * side;
}
Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value
Example
#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
20
The sum is 30
Example

program to calculate the average of five numbers.


#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{

float avg;
avg=(a+b+c+d+e)/5);
printf(“The average of five numbers=%f ”,avg);
}

Output
Going to calculate the average of five numbers
Enter five numbers
10
20
30
40
50
The average of five numbers= 30.000000

Example function with argument and with return value


Example
#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);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:
10
20
The sum is: 30
CALL BY VALUE AND REFERENCE
There are two ways in which we can pass arguments to the function or we can call the functions.

➢ Call by value
➢ Call by reference

Call by Value
In this type, the value of actual arguments is passed to the formal arguments and operation is done
on the formal arguments. Any change in the formal arguments made does not affect the actual
arguments because formal arguments are the photocopy of the actual argument. Hence, when a

function is called by the call by value method, it does not affect the actual contents of the arguments.
Changes made in the formal arguments are local to the block of the called function.

Write a program to exchange values of two variables by using 'call by value' to the function.

#include<stdio.h>
void swap(int x,int y);
main()
{

int a,b;
printf(“Enter the values:”);
a=10;
b=20;
swap(a,b);
printf(“a=%d b=%d”,a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf(“x=%d y=%d”,x,y);
}

Output
x=20 y=10
a=10 b=20

Call by Reference
In this type, instead of passing values, addresses (reference) are passed. Function operates on
addresses rather than values. Here, the formal arguments are pointers to the actual argument. In this
type, formal arguments point to the actual argument. Hence, changes made in the argument are
permanent.

Write a program to send a value by reference to the user-defined function.


#include<stdio.h>
void swap(int *x,int *y);
void main()

{
int a,b;
printf(“Enter the values:”);
a=10;

b=20;
swap(&a,&b);
printf(“a=%d b=%d”,a,b);

}
void swap(int *x,int *y)
{
int t;
t=*x;

*x=*y;
*y=t;
printf(“x=%d y=%d”,*x,*y);
}
Output

x=20 y=10

a=20 b=10

RECURSION
The C language supports recursive feature, i.e. a function is call repetitively by itself. The recursion can
be used directly or indirectly. The direct recursion function calls to itself till the condition is true. In
indirect recursion, a function calls to another function and then called function calls to the calling
function.
Example P52.
/* recursive function for factorial*/

int fact (int) ;


void main()
{
int num, f;
clrscr();
printf("\n Enter a number ;");
scanf ("%d", &num);
f=fact (num) ;
printf("\n Factorial of (%d) is (%d)",num,f);
}
int fact(int f)
{
if (f==1)
return f;
else
return f*fact(f-1);
}
OUTPUT:
Enter a number: 4
Factorial of (4) is (24)

/*recursive function for fibonnaci series*/


int fibonnaci (int x)
{
if(x<=2) return 1;
return fibonnaci(x-1)+fibonnaci(x-2);
}
main()
{
printf("\n fact(10) : %d",fact(10));
printf("\n fibonnaci(10) : %d",fibonnaci(10));
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy