Professional Documents
Culture Documents
Unit 3
Unit 3
Unit 3
An array is a special type of variable used to store multiple values of same data type at a time.
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...
Syntax for creating an array without size and with initial values
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 ;
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.
We use the following general syntax for declaring a single dimensional array...
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.
We use the following general syntax for declaring and initializing a single dimensional array with size
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...
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.
We use the following general syntax for declaring a two dimensional array...
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} } ;
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.
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
Output:
Enter array size: 5
Accept Numbers: 1 3 4 5 3
Array with Unique list: 1 3 4 5
Output:
Enter no of elements: 5 11 44 22 55 99
Smallest Element: 11
#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
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
char str[6] ;
The following declaration creates a string variable of a specific size at the time of program execution.
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...
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...
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())
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
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'.
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
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
clrscr() ;
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.
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.
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
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);
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.
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
{
int result ;
clrscr() ;
Page 30 of 50
Programming for Problem Solving Using ‘C’ Unit-III
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
}
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
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
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
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
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
3 string.h It contains all string related library functions like gets(), puts(),etc.
Page 37 of 50
Programming for Problem Solving Using ‘C’ Unit-III
This header file contains all the math operations related functions
5 math.h like sqrt(), pow(), etc.
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:
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
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);
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.
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
{
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.
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
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
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:
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
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'.
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