PPS - Unit Iii
PPS - Unit Iii
1
FUNCTIONS, STORAGE CLASSES AND STRINGS
3. Introduction.
C supports the use of library functions, which are used to carry out a number of commonly used
operations or calculations .However, C also allows programmers to define their own functions for
carrying out various individual tasks. The use of programmer-defined functions allows a large
program to be broken down into a number of smaller, self-contained components, each of which has
some unique, identifiable purpose. Thus a C program can be modularized through the intelligent use
of such functions. The use of a function avoids the need for redundant (repeated) programming of the
same instructions.
Advantages of functions
Several advantages of dividing the program into functions include:
1. Modularity
2. Reduction in code redundancy
3. Enabling code reuse
4. Better readability
Parts of a function
A function has the following parts:
1. Function prototype declaration.
2. Function definition.
2
3. Function call.
4. Actual arguments and Formal arguments.
5. The return statement.
Function Declaration
Function prototype declaration consist function return type, function name, and argument list. A
function must be declared before it is used
Syntax
return_type function_name(parameter_list);
parameter_list: type param1,type param2,type param3, etc
Examples
double sqrt(double);
int func1();
void func2(char c);
Function Definition also known as function implementation, means composing a function. Every
Function definition consists of two Parts:
1. Header of the function,
2. Body of the function.
Syntax
return_type function_name(parameter_list)
{// Function body
}
The body of a function consists of a set of statements enclosed within braces. The
return statement is used to return the result of the computations done in the called function and/or
to return the program control back to the calling function. A function can be defined in any part of
the program text or within a library.
Function Call
A function call has the following syntax:
3
A function with no arguments and no return value
Called function does not have any arguments
Not able to get any value from the calling function
Not returning any value
There is no data transfer between the calling function and called function.
Example
#include<stdio.h>
void welcome(); //function prototype declaration
int main() // calling function
{
welcome(); //function call
return 0;
}
void welcome() //called function
{
printf("Hi students..!"); function body
}
OUTPUT
Hi students..!
Example
#include <stdio.h> int
send();
int main()
{
OUTPUT
}
int send()
{
}
4
i end()
n printf("\nYou entered : %d",x);
t return 0;
x
;
int n;
x printf("\nEnter a number: ");
= scanf("%d", &n);
s return n;
Enter a number: 5
You entered: 5
OUTPUT
5
Sum of 30 and 15 is 45
Sum of 63 and 49 is 112
Sum of 952 and 321 is 1273
Example
#include <stdio.h>
int add(int x, int y);
int main()
{
int z; z=add(952,321);
printf("Result %d\n", add(30,55));
printf("Result %d\n", z);
return 0;
}
int add(int a, int b)
{
int result;
result = a+b;
return (result);
}
OUTPUT
Result = 85
Result = 1273
Call by Value
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter. Different
Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Example
1. /* C Functins - Call by Value Program */
#include<stdio.h>
#include<conio.h>
int square(int);
6
void main()
{
int num;
clrscr();
getch();
}
int square(int a)
{
a = a*a;
return a;
}
Output: Enter a number 5
Square of 5 is 25
Call by reference
In call by reference method, the address of the variable is passed to the function
as parameter. The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used
by both parameters.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
clrscr();
getch();
}
7
void swap(int *a, int *b)
{
int temp;
3.3 Recursion
A function that calls itself repetitively is known as a recursive function. And, this
technique is known as recursion. The function calls itself repetitively until certain condition is
satisfied.
The recursive function has following types of statements:
3.3.1 A statement or condition to determine if the function is calling itself again.
3.3.2 A function call which should have argument.
3.3.3 Conditional statement(if-else)
3.3.4 A return statement.
#include <stdio.h>
int main()
{
int x; long
int f;
prinf(“Enter a number:”);
8
scanf(“%d”,&x);
f=factorial(x);
printf("Factorial of %d is %ld\n",x,f); return 0;
}
long int factorial(int n)
{
if(n==0 ) //base condtion
return 1;
else
return n*factorial(n-1);
} OUTPUT
Factorial of 5 is 120
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}
Output
9
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Output
To pass an entire array to a function, only the name of the array is passed as an argument. However, notice
the use of [] after argument name in float average(float age[]). This informs the compiler that you are passing
a one-dimensional array to the function.
To pass multidimensional arrays to a function, only the name of the array is passed (similar to one
dimensional array).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
// passing multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
10
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}
Output
To pass an entire array to a function, only the name of the array is passed as an argument. However, notice
the use of [] after argument name in float average(float age[]). This informs the compiler that you are passing
a one-dimensional array to the function.
To pass multidimensional arrays to a function, only the name of the array is passed (similar to one
dimensional array).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
// passing multi-dimensional array to a function
11
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}
You can not only pass variables/values to a function, but you can also pass addresses to a function. After all,
address is also some kind of a value.
Since pointer store address, you can use pointer to accept that address in the function definition. Let's take an
example:
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
// pointer n1 and n2 stores the address of num1 and num2 respectively
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
When you run the program, the output will be:
num1 = 10
num2 = 5
Storage classes
From C compiler’s point of view, a variable name identifies some
physical location within the computer where the value of the variable is stored.
There are basically two kinds of locations in a computer where such a value
may be kept—
3. Memory
4. CPU registers.
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
12
A variable’s storage class tells us:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if initial value is not
specifically assigned.(i.e. the default value).
3. What is the scope of the variable; i.e. in which functions the value of
the variable would be available.
4. What is the life of the variable; i.e. how long would the variable exist.
Automatic Variables
These are declared inside a function in which they are to be utilized. These are
declared using a keyword auto.
Example:
auto int number;
Storage Memory.
Initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable is defined.
Example
#include<stdio.h> int
main( )
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;
OUTPUT
321
Register variables
These variables are stored in one of the machine’s register and are declared
using keyowd
register. Example
register int count;
Since register access are much faster than a memory access keeping
frequently accessed variables in the register lead to faster execution of
program.
Use register storage class for only those variables that are being used
very often in a program (loop counters).
Example
#include<stdio.h> int
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ;
} i++ ) printf ( “%d ",
i);
OUTPUT
14
1 2 3 4 5 6 7 8 9 10
Static variables
The value of static variables persists until the end of the program. It is declared
using the
static keyword.
Example
static int x;
Static variables are initialized only once, when the program is compiled.
Use static storage class only if you want the value of a variable to
persist between different function calls.
Properties of static variable are as under:
Storage Memory
Initial value Zero
Scope Local to the block in which the variable is defined
Life Value of the variable persists between different function calls
Example
#include<stdio.h
> void
increment(); int
main( )
{
increment(
);
increment(
);
increment(
); return
0;
}
void increment()
{
static int i ;
printf ( "%d\n",
} i);i=i+1;
OUTPUT
15
0 1 2
Storage Memory
Initial value Zero
Scope Global
Life As long as the program’s execution doesn’t come to an end
16
Strings
The string in C programming language is actually a one-dimensional array of
characters which is terminated by a null character '\0'. Since string is an array, the
declaration of a string is the same as declaring a char array.
char string1[30];
char str2[7] = “String”;
The following declaration creates string named “str2” and initialized with value “String”.
To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word.
Note: The C compiler automatically places the '\0' at the end of the string when it
initializes the array.
The terminating null (‘\0’) is important, because it is the only way the functions that
work with a string can know where the string ends.
17
int main( )
{
char name[ ] = “CMRCET" ; int i = 0 ;
while ( i <= 9 )
{
printf ( "%c", name[i] ) ; i++ ;
}
return 0;
}
Function Use
strlen() Finds length of a string
strlwr() Converts a string to lowercase
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strcpy() Copies a string into another
strcmp() Compares two strings
strchr() Finds first occurrence of a given character in a
string
strstr() Finds first occurrence of a given string in another
string
18
strrev() Reverses the given string
strlen() function
This function counts the number of characters present in a string. Syntax
for strlen() function is given below:
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose
length is to be found, and returns the length of the string passed.
#include
<string.h
> int
main( )
{
char str[ ]
=
"Henry" ;
int len1,
len2 ;
len1 = strlen ( str ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nThe string %s length is %d", str, len1 ) ;
printf ( "\nThe string %s length is %d\n", "Humpty
Dumpty", len2 ) ; return 0;
}
Output
The string Henry length is 5
strcpy( ) function
This function copies the contents of one string into another. Syntax for
strcpy() function is given below.
19
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.
Output
Source string =
Sayonara
Destinnation string =
Sayonara
strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination
string. Syntax for strcat( ) function is given below.
char * strcat ( char * destination, const char * source );
For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.
20
#include<
string.h>
int main( )
{
char source[ ]
="Students!" ; char
target[30] = "Hello"
; strcat ( target,
source ) ;
printf ( "\nSource string = %s",
source ) ; printf ( "\nDestination
string = %s", target ) ; return 0;
}
Output
Source string = Students!
Destination string =
HelloStudents!
strcmp( ) function
It compares two strings to find out whether they are same or different. The two
strings are compared character by character until there is a mismatch or end of one of
the strings is reached, whichever occurs first.
Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as
different characters.
Example 15: C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
21
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Output
0 4 -32
Output:
Enter a string: madam madam is palindrome
Some other palindrome strings are: civic, dad, malayalam, mom,wow etc.
22
0;
}
When you will compile the above code, it will ask you to enter a value. When
you will enter the value, it will display the value you have entered.
Long answers:
23
1. What are type qualifiers? Write a program to find Fibonacci series of a given number using
recursive and non recursive approaches.
2. What is recurstion? Write a C program to find GCD ( greatest common devisor ) of two given
integers.
7. What is recursion? Write a C program to find the factorial of a given number using recursion.
Short answers:
24