Unit 3

You might also like

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

Programming for Problem Solving Using ‘C’ Unit-III

Programming for Problem


Solving Using ‘C’
Unit-III

Arrays: definition, declaration, accessing elements, storing


elements, 2-D arrays, Multidimensional arrays, Strings and
string manipulations. Functions: Standard Library Functions:
User Defined Functions-Function prototype, function
definition, function call, Example Programs, Passing
Parameters-Call by value

Ramdas Kapila, Assistant Professor, Dept. of CSE,NSRIT


Page 1 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`

Department of Computer Science & Engineering


Programming for Problem Solving using ‘C’
(Common for Civil, ECE, MECH, EEE, CSE, CSE (DS), CSE (AI &ML)

Unit III: Arrays and Functions 10 Hours


Arrays: definition, declaration, accessing elements, storing elements, 2-D arrays, Multidimensional
arrays, Strings and string manipulations.
Functions: Standard Library Functions: User Defined Functions-Function prototype, function
definition, function call, Example Programs, Passing Parameters-Call by value
Arrays
When we work with a large number of data values we need that any number of different variables. As
the number of variables increases, the complexity of the program also increases and so the programmers
get confused with the variable names. There may be situations where we need to work with a large
number of similar data values. To make this work easier, C programming language provides a concept
called "Array".

An array is a special type of variable used to store multiple values of same data type at a time.

An array can also be defined as follows...

An array is a collection of similar data items stored in continuous memory locations with single

name.
Declaration of an Array
In C programming language, when we want to create an array we must know the datatype of values to
be stored in that array and also the number of values to be stored in that array.
We use the following general syntax to create an array...

datatype arrayName [ size ] ;

Syntax for creating an array with size and initial values

datatype arrayName [ size ] = {value1, value2, ...} ;

Syntax for creating an array without size and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;

In the above syntax, the datatype specifies the type of values we store in that array and size specifies the
maximum number of values that can be stored in that array.
Example Code
int a [3] ;
Page 2 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells
the compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of mem
ory. For the above declaration, the memory is organized as follows...

In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but
also assigns a numerical reference value to every individual memory location of an array. This reference
number is called "Index" or "subscript" or "indices". Index values for the above example are as
follows...
Accessing Individual Elements of an Array

The individual elements of an array are identified using the combination of 'arrayName' and

'indexValue'. We use the following general syntax to access individual elements of an array...

arrayName [ indexValue ] ;

For the above example the individual elements can be denoted as follows...

For example, if we want to assign a value to the second memory location of above array 'a', we use the

following statement...
Example Code
a [1] = 100 ;

The result of the above assignment statement is as follows...

Types of Arrays in C
In c programming language, arrays are classified into two types. They are as follows...
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array
Single 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

We use the following general syntax for declaring a single dimensional array...

datatype arrayName [ size ] ;

Page 3 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`

Example Code
int rollNumbers [60] ;
The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes e
ach with the name rollNumbers and tells the compiler to allow only integer values into those memory l
ocations.

Initialization of Single Dimensional Array

We use the following general syntax for declaring and initializing a single dimensional array with size

and initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;


Example Code
int marks [6] = { 89, 90, 76, 78, 98, 86 } ;
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]

89 90 76 78 98 86

The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes
each with the name marks and initializes with value 89 in first memory location, 90 in second memory
location, 76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86
in sixth memory location.
We can also use the following general syntax to intialize a single dimensional array without specifying
size and with initial values...

datatype arrayName [ ] = {value1, value2, ...} ;


The array must be initialized if it is created without specifying any size. In this case, the size of the array
is decided based on the number of values initialized.
Example Code
int marks [] = { 89, 90, 76, 78, 98, 86 } ;
char studentName [] = "btechsmartclass" ;
In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one exttra
character called \0 (NULL) at the end.
Accessing Elements of Single Dimensional Array
In c programming language, to access the elements of single dimensional array we use array name
followed by index value of the element that to be accessed. Here the index value must be enclosed in
square braces. Index value of an element in an array is the reference number given to each element at the
time of memory allocation. The index value of single dimensional array starts with zero (0) for first
element and incremented by one for each element. The index value in an array is also called
as subscript or indices.

We use the following general syntax to access individual elements of single dimensional array...

Page 4 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`

arrayName [ indexValue ]

Example Code
marks [2] = 99 ;
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]

89 90 99 78 98 86

In the above statement, the third element of 'marks' array is assinged with value '99'.
Multi Dimensional Array
An array of arrays is called as multi dimensional array. In simple words, an array created with more than
one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two
dimensional array or three dimensional array or four dimensional array or more...

Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays
are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.

Declaration of Two Dimensional Array

We use the following general syntax for declaring a two dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;


Example Code
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each
in the form of 2 rows and 3 columns.

Initialization of Two Dimensional Array


We use the following general syntax for declaring and initializing a two dimensional array with specific
number of rows and coloumns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;


Example Code
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

1 2 3

4 5 6

The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each
in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row
is initialized with values 4, 5 & 6.
We can also initialize as follows...

Page 5 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Example Code
int matrix_A [2][3] = {{1, 2, 3},{4, 5, 6} } ;

Accessing Individual Elements of Two Dimensional Array


In a c programming language, to access elements of a two-dimensional array we use array name
followed by row index value and column index value of the element that to be accessed. Here the row
and column index values must be enclosed in separate square braces. In case of the two-dimensional
array the compiler assigns separate index values for rows and columns.
We use the following general syntax to access the individual elements of a two-dimensional array...

arrayName [ rowIndex ] [ columnIndex ]


Example Code
matrix_A [0][1] = 10 ;
0 1 2
1 10 3
4 5 6

In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged
with value 10.
Applications of Arrays in C
In c programming language, arrays are used in wide range of applications. Few of them are as follows...
● Arrays are used to Store List of values
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.

● Arrays are used to Perform Matrix Operations


We use two dimensional arrays to create matrix. We can perform various operations on matrices using
two dimensional arrays.

● Arrays are used to implement Search Algorithms


We use single dimensional arrays to implement search algorihtms like ...
1. Linear Search
2. Binary Search
● Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorihtms like ...
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,
● Arrays are used to implement Datastructures
Page 6 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
We use single dimensional arrays to implement datastructures like...
1. Stack Using Arrays 2. Queue Using Arrays

● Arrays are also used to implement CPU Scheduling Algorithms

Calculate Average
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, 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];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
Example Programs:
1. C Program for deletion of an element from the specified location from an
Array
#include <stdio.h>
int main()
{
int arr[30], num, i, loc;
Page 7 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
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]);
return (0);
}

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

2. C Program to delete duplicate elements from an array


int main()
{
int arr[20], i, j, k, size;
printf("\nEnter array size: ");
scanf("%d", &size);
printf("\nAccept Numbers: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size;)
{
if (arr[j] == arr[i])
{
for (k = j; k < size; k++)
{
arr[k] = arr[k + 1];
}
size--;
}
else j++;
Page 8 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
}
}
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return (0); }

Output:
Enter array size: 5
Accept Numbers: 1 3 4 5 3
Array with Unique list: 1 3 4 5

3. C Program to find smallest element in an array


#include<stdio.h> int
main()
{
int a[30], i, num, smallest;
printf("\nEnter no of elements :");
scanf("%d", &num); //Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]); //Consider first element as smallest smallest =
a[0];
for (i = 0; i < num; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
// Print out the Result
printf("\nSmallest Element : %d", smallest);
return (0);
}

Output:
Enter no of elements: 5 11 44 22 55 99
Smallest Element: 11

4. C Program to find largest element in an array

#include <stdio.h>
int main()
{
int a[30], i, num, largest;

Page 9 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
printf("\nEnter no of elements :");
scanf("%d", &num); //Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as largest
largest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] > largest)
{ largest = a[i];
}
}
// Print out the Result
printf("\nLargest Element : %d", largest);
return (0);
}

Output:
Enter no of elements : 5 11 55 33 77 22 Largest
Element : 77

5. C Program to reverse an array elements in an array


#include<stdio.h>
int main()
{
int arr[30], i, j, num, temp;
printf("\nEnter no of elements : ");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
j = i - 1; // j will Point to last Element
i = 0; // i will be pointing to first element
while (i < j)
{
temp = arr[i];
Page 10 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
arr[i] = arr[j];
arr[j] = temp;
i++; //
increment i j--;
//decrement j
}
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++)
{
printf("%d \t", arr[i]);
}
return (0);
}
Output:
Enter no of elements: 5 11 22 33 44 55
Result after reversal : 55 44 33 22 11

Strings in C
String is a set of characters that are enclosed in double quotes. In the C programming language, strings
are created using one dimension array of character datatype. Every string in C programming language is
enclosed within double quotes and it is terminated with NULL (\0) character. Whenever c compiler
encounters a string value it automatically appends a NULL character (\0) at the end. The formal
definition of string is as follows...

String is a set of characters enclosed in double quotation marks. In C programming, the string is a

character array of single dimension.


In C programming language, there are two methods to create strings and they are as follows...
1. Using one dimensional array of character datatype ( static memory allocation )
2. Using a pointer array of character datatype ( dynamic memory allocation )
Creating string in C programming language
In C, strings are created as a one-dimensional array of character datatype. We can use both static and
dynamic memory allocation. When we create a string, the size of the array must be one more than the
actual number of characters to be stored. That extra memory block is used to store string termination
character NULL (\0). The following declaration stores a string of size 5 characters.

char str[6] ;

The following declaration creates a string variable of a specific size at the time of program execution.

char *str = (char *) malloc(15) ;

Page 11 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Assigning string value in C programming language
String value is assigned using the following two methods...
1. At the time of declaration (initialization)
2. After declaraation
Examples of assigning string value
int main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'s','m','a','r','t'};
char name2[6] = {'s','m','a','r','t'};
char title[20];
*title = "btech smart class";
return 0;
}
Reading string value from user in C programming language
We can read a string value from the user during the program execution. We use the following two
methods...

1. Using scanf() method - reads single word


2. Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent string in scanf() and
printf() methods.
Examples of reading string value using scanf() method
#include<stdio.h>
#include<conio.h>
int main(){
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
When we want to read multiple words or a line of text, we use a pre-defined method gets().
The gets() method terminates the reading of text with Enter character.
Examples of reading string value using gets () method
#include<stdio.h>
#include<conio.h>

Page 12 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
int main(){
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;}
C Programming language provides a set of pre-definied functions called String Handling Functions to
work with string values. All the string handling functions are defined in a header file called string.h.
String Handling Functions in C
C programming language provides a set of pre-defined functions called string handling functions to
work with string values. The string handling functions are defined in a header file called string.h.
Whenever we want to use any string handling function we must include the header file called string.h.
The following table provides most commonly used string handling function and their use...

Function Syntax (or) Example Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if
string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case
(upper or lower)

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case
(similar to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case.

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in
string1

Page 13 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of character 'b' in
string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in


string1

strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.

strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.

strrev() strrev(string1) It reverses the value of string1

String Handling Functions In C Language


1) 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.
• Note that the null character “\0‟ available at the end of a string is not counted.
2) strcpy( ) Function :
strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given
below.
Syntax: char * strcpy (char * destination, const char * source);
Example:
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, entire source string value won’t be copied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20
characters from source string will be copied into destination string and remaining 10 characters won’t be
copied and will be truncated.
Example : char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.

Page 14 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
3) strcat( ) Function :
strcat( ) function in C language concatenates two given strings. It concatenates source string at the end
of destination string. Syntax for strcat( ) function is given below.
Syntax : char * strcat ( char * destination, const char * source );
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0′).
• In strcat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after strcat(
) operation.
Program : The following program is an example of strcat() function
#include <stdio.h>
#include <string.h>
int main( )
{ char source[ ] = “ ftl” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}

Output :
Source string = ftl
Target string = welcome to
Target string after strcat() = welcome to ftl

4) Strncat() function :
strncat( ) function in C language concatenates (appends) portion of one string at the end of another
string.
Syntax : char * strncat ( char * destination, const char * source, size_t num );
Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.
As you know, each string in C is ended up with null character (‘\0′).
In strncat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after strncat(
) operation.
Page 15 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Program: The following program is an example of strncat() function
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] =”" ftl” ;
char target[ ]= “welcome to” ;
printf ( “\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strncat ( target, source, 3 ) ;
printf ( "”\n Target string after strncat( ) = %s”, target ) ;
}
Output :
Source string = ftl
Target string = welcome to
Target string after strncat()= welcome to ft
5) strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are same. If length of
string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value.
Syntax : int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example :
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the first
mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer variable as
follows:
int n;
n = strcmp(city, town);
6) strcmpi() function :
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not case sensitive. i.e.,
“A” and “a” are treated as same characters. Whereas, strcmp() function treats “A” and “a” as different
characters.
• strcmpi() function is non standard function which may not available in standard library.
• Both functions compare two given strings and returns zero if they are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value.
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Syntax : int strcmpi ( const char * str1, const char * str2 );

Page 16 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Example :
m = 0.m=strcmpi(“ DELHI ”, “ delhi ”);
7) strlwr() function :
strlwr() function converts a given string into lowercase.
Syntax : char *strlwr(char *string);
strlwr() function is non standard function which may not available in standard library in C.
Program : In this program, string ”MODIFY This String To LOwer” is converted into lower case using
strlwr( ) function and result is displayed as “modify this string to lower”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “MODIFY This String To Lower”;
printf(“%s\n”, strlwr (str));
return 0;
}
Output :
modify this string to lower
8) strupr() function :
strupr() function converts a given string into uppercase.
Syntax : char *strupr(char *string);
strupr() function is non standard function which may not available in standard library in C.
Program : In this program, string ”Modify This String To Upper” is converted into uppercase using
strupr( ) function and result is displayed as “MODIFY THIS STRING TO UPPER”.

#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “Modify This String To Upper”;
printf(“%s\n”, strupr(str));
return 0;
}
Output :
MODIFY THIS STRING TO UPPER
9) strrev() function :
strrev() function reverses a given string in C language.
Page 17 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Syntax : char *strrev(char *string);
strrev() function is non standard function which may not available in standard library in C.
Example :
char name[20]=”ftl”; then
strrev(name)= ltf
Program : In below program, string “Hello” is reversed using strrev( ) function and output is displayed
as “olleH”.
#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
10) strchr() function :
strchr() function returns pointer to the first occurrence of the character in a given string.
Syntax : char *strchr(const char *str, int character);
Program : In this program, strchr( ) function is used to locate first occurrence of the character ‘i’ in the
string ”This is a string ”. Character ‘i’ is located at position 3 and pointer is returned at first occurrence
of the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[25] =”This is a string “;
char *p;
p = strchr (string,'i');
printf (“Character i is found at position %d\n”,p-string+1);
printf (“First occurrence of character \”i\” in \”%s\” is” \” \”%s\””,string, p);
return 0;
}
Output :
Character i is found at position 3
First occurrence of character “i” in “This is a string” is “is is a string”
Page 18 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
11) strstr() function :
strstr( ) function returns pointer to the first occurrence of the string in a given string.
Syntax : char *strstr(const char *str1, const char *str2);
Program : In this program, strstr( ) function is used to locate first occurrence of the string “test” in the
string ”This is a test string for testing”. Pointer is returned at first occurrence of the string “test”.
#include <stdio.h>
#include <string.h>
int main( )
{
char string[55] =”This is a test string for testing”;
char *p;
p = strstr (string, ”test”);
if(p)
{
printf(“string found\n” );
printf (“First occurrence of string \”test\” in \”%s\” is”\” \”%s\””,string, p);
}
else printf(“string not found\n” );
return 0;
}
Output :
String found
First occurrence of ”test” in “this is a test string for testing” is “testing string for testing”
12) atoi() function :
It converts string-value to numeric-value and it converts a numeric-string value to equivalent integer-
value.
Syntax : int atoi(string);
Example :
printf(“output=%d”, atoi(“123”)+atoi(“234”));
This printf() will print 357
13) atol() function :
converts a long int string value to equivalent long integer value.
Syntax : long int atol(string);
Example :
printf(“output=%d”, atol(“486384”)-atol(“112233”));
This statement will print 374151
14) atof() function :
converts a floating point text format value to double value.
Syntax : int atoi(string);
Page 19 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Example :
printf(“%1f”,atof(“3.1412”)*5*5);
This statement will print 78.530000
15) itoa(),ltoa(),ultoa() :
These functions converts a given number(int/long int/unsigned long int) to equivalent text format based
on the given numbering system radix value.These functions take three arguments, the numeric value,
target string address in which the value to be stored and radix value. Finally returns the target string
address, so that function-call can be used as argument/expression.
Syntax : char* itoa(int value, char *targetstringaddress, int radix );
Example :
Char temp[50];
Printf(“output=%s”, itoa(45,temp,2));
Output : 101101
Program : Write a C program to count the number of vowels present in a sentence.
# include<stdio.h>
# include<conio.h>
# include<string.h>
main( )
{
char st[80], ch;
int count = 0, i;
clrscr( );
printf(“ \n Enter the sentence: \n”);
gets(st);
for( i=0; i<strlen(st); i++)
switch(st [i ])
{
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
case ‘a’:
case ‘e’:
case ‘I’:
case ‘o’:
case ‘u’:
count ++;
break;

Page 20 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
}
printf(“\n %d vowels are present in the sentence”, count);
getch( );
}
 When this program is executed, the user has to enter the sentence.
 Note that gets( ) function is used to read the sentence because the string has white spaces
between the words.
 The vowels are counted using a switch statement in a loop.
 Note that a count++ statement is given only once to execute it for the cases in the switch
statement.
Output :
Enter the sentence :
This is a book
5 vowels are present in the sentence.
Program : Write a C program to count no of lines, words and characters in a given text.
# include<stdio.h>
# include<string.h>
# include<conio.h>
main()
{
char txt[250], ch, st[30];
int ins, wds, chs, i;
printf(“ \n Enter the text, type $ st end \n \n”);
i=0;
while((txt[i++]= getchar( ) ) ! =’$’);
i--;
st[ i ] = ‘\0’;
ins = wds = chs = 0;
i=0;
while(txt[ i ]!=’$’)
{
switch(txt[ i ])
{

case ‘,’:
case ‘!’:
case ‘\t’:
case ‘ ‘:
{
wds ++;
chs ++;
break;
}
case ‘?’:
case ‘.’:
{
wds ++;
chs ++;
Page 21 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
break;
}
default:chs ++;
break;
}
i++;
}
printf(“\n\n no of char (incl.blanks) = %d”, chs);
printf(“\n No. of words = %d”, wds);
printf(“\n No of lines = %d”, ins);
getch() ;
}

Output:
Enter the text, type $ at end
What is a string? How do you initialize it? Explain with example.
With example: $
No of char: (inch. Blanks) = 63
No of words = 12
No of lines =1.

Page 22 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
Functions: User Defined Functions-Function prototype, function definition,
function call, Example Programs, Passing Parameters-Call by value

DESIGNING STRUCTURED PROGRAMS:


Structured programming is a programming technique in which a larger program is divided
into smaller subprograms to make it easy to understand, easy to implement and makes the code
reusable, etc. Structured programming enables code reusability. Code reusability is a method of writing
code once and using it many times. Using a structured programming technique, we write the code once
and use it many times. Structured programming also makes the program easy to understand, improves
the quality of the program, easy to implement and reduces time.

Advantages of Structured Programming Approach:


1. Easier to read and understand
2. User Friendly
3. Easier to Maintain
4. Mainly problem based instead of being machine based
5. Development is easier as it requires less effort and time
6. Easier to Debug
7. Machine-Independent, mostly.
Disadvantages of Structured Programming Language:
1. Same code repetition
2. Lack of encapsulation
3. Lack of information hiding
In C, the structured programming can be designed using functions .Using functions, we can
divide the larger program into smaller subprograms and these subprograms are implemented
individually. Every subprogram or function in C is executed individually.

Page 23 of 50
Programming for Problem Solving Using ‘C’ Unit-III
`
FUNCTIONS IN C:
Function is a subpart of a program used to perform a specific task and is executed individually.
When we write a program to solve a larger problem, we divide that larger problem into smaller
sub problems and are solved individually to make the program easier. In C, this concept is implemented
using functions. Functions are used to divide a larger program into smaller subprograms such that the
program becomes easy to understand and easy to implement.
Functions in C program have following parts as:
 The function prototype (or) function declaration.
 The calling of the function.
 The definition of the function.
 Return value
Function Prototype/Function declaration:
The function prototype defines:
 The name of the function.
 The type of value returned by the function.
 The number of arguments passed to the function and the data type of the arguments passed to
the function.
If the function does not return a value or if no arguments are passed to the function, the void keyword
should be used.
Syntax: return_type function_name (argument list);
Eg: void myfunction1(void); /* no return or arguments */
int myfunction2(void); /* returns an int, no arguments */
void myfunction3(int); /* no return, one int argument */

int myfunction( int, int ); /* returns an integer and takes two integer arguments*/
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 parameters as it is
declared in the function declaration.
Syntax: returntype function_name
(argument_list); Eg: int sum(a,b);

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

Page 24 of 50
Function Definition:
It contains the actual statements which are to be executed. when the function is
called the control comes to the definition of function. only one value can be returned from the
function.
Syntax: return_type function_name (argument list)
{
function body;
}
Eg:
int myfunction( int x, int y )
{
double z; int a;

. return(a);
}

Return Value:
A 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. The keyword return is used to return a
value.
Example without a return value:
void hello()
{
printf("hello c");
}
Example with return value:
int get()
{
return 10;
}
Example Program
#include<stdio.h>

#include<conio.h>

void main()

{
Programming for Problem Solving Using ‘C’ Unit-III

int num1, num2, result ;


int addition(int,int) ; // function
declaration

clrscr() ;

printf("Enter any two integer numbers : ") ;


scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call


printf("SUM = %d", result);

getch() ;
}
int addition(int a, int b) // function definition
{
return a+b ;
}

TYPES OF FUNCTIONS:
There are two types of functions in C programming:

Library/System Functions: The function whose definition is defined by the system is called as
system defined function. These are the functions declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc. These are also called Standard Functions or Pre-
Defined Functions.
The list of mostly used header files is given in the following table.

SN Header Description file

This is a standard input/output header file. It contains all the library


functions regarding standard input/output.
1 stdio.h

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.

Page 26 of 50
Programming for Problem Solving Using ‘C’ Unit-III

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.

USER DEFINED FUNCTIONS:


The function whose definition is defined by the user is called as user defined function.
These functions 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.
General Form of a User defined Function:
return data type function-name(argument list) argument declaration
{
Local variable declaration; Executable statements;

return(expression);
}
User defined Functions in C program has following parts as:
 The function prototype (or) function declaration.
 The calling of the function.
 The definition of the function.
 Return value
Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in
the program.

Page 27 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Syntax of function prototype:


return-type functionname(type1 argument1, type2
argument2, ...); Example: int addnumbers(int a, int b);

This function prototype which provides the following information to the compiler:
name of the function is addNumbers()
return type of the function is int
two arguments of type int are passed to the function
Calling a function:
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 parameters as it is
declared in the function declaration.
Syntax: returntype function_name
(argument_list); Eg: int sum(a,b);

The arguments are of two types:


Formal Arguments:
The arguments which are given at the time of function declaration or function definition are called
formal arguments.
Actual Arguments:
The arguments which are given at the time of function calling are called actual arguments.
Function definition
Function definition contains the block of code to perform a specific task. In our example, adding two
numbers and returning it.
Syntax:
returntype functionname(type1 argument1, type2 argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is transferred to the function definition. and,
the compiler starts executing the codes inside the body of a function.
Return Statement:
The return statement terminates the execution of a function and returns a value to the
Page 28 of 50
Programming for Problem Solving Using ‘C’ Unit-III

calling function. The program control is transferred to the calling function after the return statement.
Syntax: return
(expression); Example:
return
a;

return (a+b);
The type of value returned from the function and the return type specified in the function prototype
and function definition must match.

Types of user defined functions in C:


Depending upon the presence of arguments and the return values, user defined functions
can be classified into five categories.
1. Function without arguments and without return values
2. Function without arguments and with return value
3. Function with arguments and without return values
4. Function with arguments and one return value
5. Function with multiple return values

1: Function without arguments and without return values


Function with no argument means the called function does not receive any data from
calling function and Function with no return value means calling function does not receive any data
from the called function. So there is no data transfer between calling and called function.
Example:
#include<stdio.h>

Page 29 of 50
Programming for Problem Solving Using ‘C’ Unit-III

#include<conio.h>
void addition() ; // function declaration
void main()
{
addition() ; // function call
getch();
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
OUTPUT:
Enter any two integer numbers :
3 4
Sum =7

2. Function without arguments and with return value


In this type of functions there is no data transfer from calling-function to called-function
(arguments) but there is data transfer from called function to calling-function (return value). The
execution control jumps from calling-function to called function and executes called function, and
finally comes back to the calling function along with a return value.
Example:
#include<stdio.h>
#include<conio.h>
int addition() ; // function
declaration void main()

{
int result ;

clrscr() ;
Page 30 of 50
Programming for Problem Solving Using ‘C’ Unit-III

result = addition() ; // function call

printf("Sum = %d", result) ;

getch() ;

}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

return (num1+num2) ;
}
OUTPUT:
Enter any two integer numbers:
4 4
Sum =8

3. Function with arguments and without return values:


In this type of functions there is no data transfer between calling function and called
function.
Simply the execution control jumps from calling-function to called function and executes
called function, and finally comes back to the calling function.
Example:
#include<stdio.h>
#include<conio.h>
void addition(int,int) ; // function declaration
void main()
{
int num1,num2;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2); addition(num1,num2) ; // function call
getch() ;
Page 31 of 50
Programming for Problem Solving Using ‘C’ Unit-III

}
void addition(int a, int b) // function definition
{
int sum; sum=a+b;
printf("Sum = %d", sum ) ;
}
OUTPUT:
Enter any two integer numbers:
5 4
Sum =9

4. Function with arguments and one return value:


In this type of functions there is data transfer from calling-function to called-function
(parameters) and also from called function to calling-function (return value). The execution control
jumps from calling-function to called function along with parameters and executes called function,
and finally comes back to the calling function along with a return value.
Example: #include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}

Page 32 of 50
Programming for Problem Solving Using ‘C’ Unit-III

OUTPUT:
Enter any two integer numbers: 6 4
Sum =10
5. Function with multiple return values:
we can use functions which can return multiple values by using input parameters and
output parameters. Those parameters which are used to receive data are called input parameters and
the parameters used to send data are called output parameters. This is achieved by using address
operator(&) and indirection operator(*).
Example:
#include <stdio.h>
void area_volume(int l, int *a, int *v); //function prototype
void main()
{
int l,a,v;
printf("Enter the side of square :");
scanf("%d",&l); area_volume(l,&a,&v); //function call
printf("Area = %d\n Volume = %d",a,v);
getch();
}
void area_volume(int l, int *a, int *v)
{
*a = l*l;
*v = l*l*l;
}
In the above program l is input argument, a and v are output arguments. In the function call,
we pass actual value of l whereas addresses of a and v are passed.

INTER-FUNCTION COMMUNICATION:
A function is a self-contained blocks or sub program that perform a special task when it
is called. Whenever a function is called to perform a specific task, then the called function
performs that task and the result is returns back to the calling function. The calling and called
functions need to communicate to exchange data. The data flow between the calling and called
functions to perform a specific task are known as inter function communication.
Different methods for transferring data between calling and called function is as

Page 33 of 50
Programming for Problem Solving Using ‘C’ Unit-III

follows. The data flow between the calling and called functions can be divided into
three strategies:

1. Downward flow
2. Upward flow
3. Bi-directional flow

1. Downward flow:- In this type of inter function communication, the data is transferred from
calling function to called function but not from called function to calling function. The
functions with parameters and without return value are considered under downward
communication. In the case of downward communication, the execution control jumps from
calling function to called function along with parameters and executes the function definition,
and finally comes back to the calling function without any return value.
Ex: - [Refer program for with arguments and without return values]
2. Upward flow:- In this type of inter-function communication, the data is transferred from called
function to calling-function but not from calling-function to called-function. The functions
without parameters and with return value are considered under upward
communication. In the case of upward communication, the execution control jumps from
calling-function to called-function without parameters and executes the function definition,
and finally comes back to the calling function along with a return value
Ex:- [Refer program for without arguments and with return values]
3. Bi-directional Flow: In this type of inter-function communication, the data is transferred from
calling-function to called function and also from called function to calling-function. The
functions with parameters and with return value are considered under bi-directional
communication. In the case of bi-directional communication, the execution control jumps
from calling-function to called function along with parameters and executes the function
definition and finally comes back to the calling function along with a return value.
Ex:- [Refer program for with arguments and with return values]

Page 34 of 50
Programming for Problem Solving Using ‘C’ Unit-III

PARAMETER PASSING TECHNIQUES IN C:


When a function gets executed in the program, the execution control is transferred from
calling-function to called function and executes function definition, and finally comes back to the
calling function. When the execution control is transferred from calling-function to called-
function it may carry one or number of data values. These data values are called as parameters.

Parameters are the data values that are passed from calling function to called function.
In C, there are two types of parameters and they are as follows...
1. Actual Parameters

2. Formal Parameters

The actual parameters are the parameters that are specified in calling function.
The formal parameters are the parameters that are declared at called function. When a
function gets executed, the copy of actual parameter values is copied into formal
parameters.

In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...
1. Call by Value
2. Call by Reference

1. Call by Value
In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called function. The
changes made on the formal parameters do not effect the values of actual parameters. That
means, after the execution control comes back to the calling function, the actual parameter
values remains same.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int,int) ; // function declaration clrscr() ;
num1 = 10 ; num2 = 20 ;
Page 35 of 50
Programming for Problem Solving Using ‘C’ Unit-III

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ; temp = a ; a = b ;
b = temp ;
}
Output:

Call by Reference:
In call by reference parameter passing method, the address of the actual parameters is passed to the
called function and is received by the formal parameters (pointers). Whenever we use these formal
parameters in called function, they directly access the memory locations of actual parameters. So
the changes made on the formal parameters effects the values of actual parameters.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int *,int *) ; // function declaration clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
Page 36 of 50
Programming for Problem Solving Using ‘C’ Unit-III

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ; temp = *a ;
*a = *b ;
*b = temp ;
}
Output:

STANDARD FUNCTIONS:
Library functions in C language are inbuilt functions which are grouped together and placed
in a common place called library.Each library function in C performs specific
operation.These library functions are created by the persons who designed and created C
compilers.All C standard library functions are declared in many header files which are
saved as file_name.h.
We include these header files in our C program using “#include<file_name.h>” command to
make use of the functions in the header files.
Below are the some standard functions in C

SN Header file Description

This is a standard input/output header file. It contains all the library


functions regarding standard input/output.
1 stdio.h

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.

This header file contains all the general library functions

Page 37 of 50
Programming for Problem Solving Using ‘C’ Unit-III

4 stdlib.h like malloc(), calloc(), exit(), etc.

This header file contains all the math operations related functions
5 math.h 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.

Functions in stdio.h:
printf(): This function is used to print the character, string, float, integer values onto the output
screen
scanf() This function is used to read a character, string, numeric data from keyboard.
sprint() writes formatted output to
string sscanf() Reads formatted input
from a string Functions in conio.h:

clrscr() This function is used to clear the output screen.


getchar() It reads character from keyboard
Functions in string.h:
strcat ( ): Concatenates str2 at the end of str1
strcpy ( ): Copies str2 into str1
strlwr ( ): Converts string to lowercase
Functions in stdlib.h:
malloc(): This function is used to allocate space in memory during the execution of the
program.

calloc() : This function is also like malloc () function. But calloc () initializes the
allocated memory to zero. But, malloc() doesn’t

realloc(): This function modifies the allocated memory size by malloc () and calloc
() functions to new size
Page 38 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Functions in Math.h:
“math.h” header file supports all the mathematical related functions in C language.All the
arithmetic functions used in C language are available in this header file.
The following are the some standard functions in math.h
Absolute Value Function(abs):This function returns the absolute value of given number
irrespective of its sign.We use abs() for integers,labs() for long int,llabs() for long long int.
Syntax: int abs(int number);
We use fabs() for double,fabsf() for float,fabsl() for long double variables
Syntax: double fabs(double number);
Eg: abs(3); returns 3
abs(-3.4) returns 3.4
Ceiling Function(ceil):
ceil( ) function rounds up the given number and returns nearest integer value which is
greater than or equal to the argument passed to this function.
Syntax: double ceil (double x);
We use ceil() for double,ceilf() for float,ceill() for long double values.
Eg: ceil(-1.9)
return
s -1.0 ceil(1.8)
return
s 2.0

Floor Functions(floor):
floor() function returns the nearest integer which is less than or equal to the argument
passed to this function.We use floor() for double values,floorf() for float values,floorl() for long
double values.
Syntax: double floor (double x);
Eg: floor(-1.1) returns -1.0

floor(1.9) returns 1.0

Round functions(round):
round( ) function in C returns the nearest integer value of the float/double/long
double argument passed to this function.

Page 39 of 50
Programming for Problem Solving Using ‘C’ Unit-III

If decimal value is from ”.1 to .5″, it returns integer value less than the argument. If decimal value
is from “.6 to .9″, it returns the integer value greater than the argument.
We use round() for double values,roundf() for float values,roundl() for long double values.
Syntax: double round (double a);

Eg: round(1.9) returns 2

Round(2.4) returns 2
Truncate Functions:
These are used to remove digits after decimal point and return the modified decimal number.We
use trunc() for double values,truncf() for float values,truncl() for long double values.
Syntax : double trunc(double x);
Eg: trunc(-1.1) returns -1.0
trunc(1.9) return 1.0

Power Function(pow): The pow() function takes two arguments (base value and power value)
and, returns the power raised to the base number.
Syntax: double pow(double x, double y);
Here, x − The base
value. y − The
power value.

Eg: p = pow(2, 3); //returns p=8


Square root Function(sqrt): The function sqrt() takes a single argument and returns the square
root of that argument.
Syntax: double sqrt(double
arg); Eg: int x = 6;

double result;
result = sqrt(double(x)); // results 2.449490
Random numbers(rand,srand):
A random number is a number selected from a set in which all members have the same
probability of being selected. Random numbers has many uses in computer science, art, statistics,
cryptography, gaming.

Page 40 of 50
Programming for Problem Solving Using ‘C’ Unit-III

rand() and srand() in C:


rand (): rand() function is used in C to generate random numbers. If we generate a sequence of
random number with rand() function, it will create the same sequence again and again every
time program runs. Say if we are generating 5 random numbers in C with the help of rand() in a
loop, then every time we compile and run the program our output must be the same sequence of
numbers.
Syntax: int rand(void);
returns a random number in the range of 0 to RAND_MAX.
Eg: C program to generate same series of random numbers in each run.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i;// This program will create same sequence of random numbers on every program run

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


printf(" %d ", rand());
getch();
}
Output 1:
453 1276 3425 89
Output 2:
453 1276 3425 89
Output n:
453 1276 3425 89
srand(): The srand() function sets the starting point for producing a series of random integers.
Syntax: void srand( unsigned seed ):
Seed values are used to make a random start
Eg: C program to generate different series of random numbers in each run.
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void main()
Page 41 of 50
Programming for Problem Solving Using ‘C’ Unit-III

{
int i;
// This program will create different sequence of random numbers on every program run
// Use current time as seed for random generator srand(time(0));
for( i = 0; i<5; i++)
printf(" %d ", rand());
getch();
}
Output 1:
453 1432 325 89
Output 2:
8976 21234 45 8975
Output n:
563 9873 12321 24132
In the above program call to srand(time(0)) used as the seed. However, time() returns a time_t
value which vary everytime and hence the random number vary for every program call.

PASSING ARRAYS TO A FUNCTION:


Just like variables, array can also be passed to a function as an argument.We can pass
arrays in three different ways
1. Passing individual elements
2. Passing the whole array
3. Passing array as constant
1. Pass individual elements:
We can pass individual elements by either passing their data values or by passing
their addresses.
Passing Data Values: We pass data values ie., individual array elements just like we pass any
other data values to the function.

Page 42 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Eg:
#include <stdio.h>
void display(int age1, int age2)
{
printf("%d \t %d\n", age1,age2);
}
void main()
{
int ageArray[] = {2, 8, 4, 12};
// Passing second and third elements to display()
display(ageArray[1], ageArray[2]);
getch();
}
Output:
8 4
Passing Addresses: We can pass the address of an individual element in an array is just like
we can pass the address of any variables

Eg:
#include <stdio.h>
void display(int *age1, int *age2)
{
printf("%d \t %d\n", *age1,*age2);
}
void main()
{
Page 43 of 50
Programming for Problem Solving Using ‘C’ Unit-III

int ageArray[] = {2, 8, 4, 12};


// Passing second and third elements to display()
display(&ageArray[1],&ageArray[2]);

getch();
}
Output:
8 4

2. Pass the whole array: For passing whole array we use array name as the actual parameter. In
the called function we declare that the corresponding formal parameter as an array.We can pass
both fixed length and variable length arrays to a function.
Eg: Calculating sum of values by passing a fixed length array to function
#include <stdio.h>
float calculateSum(float age[]); void main()
{ float result;
float arr[] = {23.4, 55.2, 22.6, 3.3, 40.5, 18.5};// age array is passed to calculateSum()
result = calculateSum(arr); printf("Result = %.2f", result);
getch();
}
float calculateSum(float arr[])
{
int i;
float sum = 0.0;
for ( i = 0; i < 6; ++i)
{
sum =sum+ arr[i];
}
return sum;
}
Output:
Result = 162.50

Page 44 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Eg: Calculating sum of values by passing a fixed length array to function


#include<stdio.h>
int sumofnum(int a[], int size)
{
int addition = 0; int i;
for(i = 0; i < size; i++)
{
addition = addition + a[i];
}
return addition;
}
void main()
{
int i, size, a[10]; int addition;
printf("Please Enter the Size of an Array: "); scanf("%d", &size);
printf("\nPlease Enter Array Elements\n"); for(i = 0; i < size; i++)
{
scanf("%d", &a[i]);
}
addition = sumofnum(a, size);
printf("Sum of All Elements in an Array = %d \n", addition); getch();
}
Output:

3. Passing array as constant: When a function receives an array as constant then it doesn’t
change it.To declare an array as constant, we prefix its type with type qualifier const
Syntax: datatype functionname (const datatype arrayname[],datatype size);
Eg: double avg(const int arr[],int size);

Page 45 of 50
Programming for Problem Solving Using ‘C’ Unit-III

RECURSION:
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Recursion always consists of two main parts.
1. A terminating case that indicates when the recursion will finish
2. Call to itself that must make progress towards the terminating case.
Syntax of Recursive Function:
returntype recursive_func (argument list)
{
statements;
... ... ...
recursive_func (actual argument);
... ... ...
}
Flowchart of Recursion:

Eg 1: Program to find factorial of a given number using recursion


We can understand the above program of the recursive method call by the figure given below:

Program:
#include <stdio.h>
int factorial(int);
void main()
{
Page 46 of 50
Programming for Problem Solving Using ‘C’ Unit-III

int num,result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
getch();
}
int factorial(int num)
{
if (num = = 0 || num = = 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}

Output:
Enter a number to find it's
Factorial: 6 The Factorial of 6 is
720.

Page 47 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Eg 2: C Program to print Fibonacci series using recursion


#include<stdio.h>
void printFibonacci(int n)
{
static int n1=0,n2=1,n3; if(n>0)
{
n3 = n1 + n2; n1 = n2;
n2 = n3; printf("%d ",n3);
printFibonacci(n-1);
}
}
void main()
{
int n;
printf("Enter the number of elements: "); scanf("%d",&n);
printf("Fibonacci Series: "); printf("%d %d ",0,1);
printFibonacci(n-2); //n-2 because 2 numbers are already printed getch();
}
Output:
Enter the number of elements: 5 0 1 1 2 3
Advantages of Recursion :
1. Reduce unnecessary calling of function.
2. Through Recursion one can Solve problems in easy way while its iterative solution is very
big and complex.
Disadvantages/Limitations of Recursion :
1. Recursive solution is always logical and it is very difficult to trace.(debug and understand).
2. In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
3. Recursion takes a lot of stack space, usually not considerable when the program is small and
running on a PC.
4. Recursion uses more processor time.

Page 48 of 50
Programming for Problem Solving Using ‘C’ Unit-III

APPLICATION OF RECURSION:
TOWER OF HANOI:
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of
the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

Approach:
Take an example for 2 disks :
Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.

Step 1: Shift first disk from 'A' to 'B'.


Step 2: Shift second disk from 'A' to 'C'.
Step 3: Shift first disk from 'B' to 'C'.

The pattern here is :


Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.

Page 49 of 50
Programming for Problem Solving Using ‘C’ Unit-III

Program:

#include <stdio.h>
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return 0;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
void main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods getch();
}

Output:

X
Ramdas Kapila
Assistant Professor, NSRIT
Page 50 of 50

You might also like