0% found this document useful (0 votes)
38 views24 pages

PPS - Unit Iii

Uploaded by

Aamer Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views24 pages

PPS - Unit Iii

Uploaded by

Aamer Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

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.

3.1. Function definition


A Function is a self-contained block of statement that performs a specific task when
called. A function is also called as sub program or procedure or subroutine.
Every C Program can be thought of as a collection of these functions. One of these functions must be
called main. If a program contains multiple functions, their definitions may appear in any order,
though they must be independent of one another. That is, one function definition cannot be embedded
within another. A function will carry out its intended action whenever it is accessed (i.e., whenever
the function is "called") from some other portion of the program. The same function can be accessed
from several different places within a program. Once the function has carried out its intended action,
control will be returned to the point from which the function was accessed. Generally, a function will
process information that is passed to it from the calling portion of the program, and return a single
value. Information is passed to the function via special identifiers called arguments (also called
parameters), and returned via the return statement. Some functions, however, accept information but
do not return anything (as, for example, the library function print) , whereas other functions (e.g., the
library function scanf ) return multiple values.

Generally, the functions are classified into two types:


1. Standard functions
2. User-defined functions.
The Standard functions are also called library functions or built-in functions. All standard
functions, such as sqrt(), abs(), log(), sin() etc. are provided in the library of function. But, most
of the applications need other functions than those available in the software, those are known as
user-defined functions.

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:

<function name>(<argument list>);


Example:
sum(a,b);

3.2 Types of functions


Functions can be divided into 4 categories:
3.2.1 A function with no arguments and no return value
3.2.2 A function with no arguments and a return value
3.2.3 A function with an argument or arguments and returning no value
3.2.4 A function with arguments and returning a values

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..!

A function with no arguments and a return value


 Does not get any value from the calling function
 Can give a return value to calling program

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

A function with an argument(s) and returning no value


 A function has argument(s).
 A calling function can pass values to function called , but calling function not receive any
value.
 Data is transferred from calling function to the called function but no data is transferred
from the called function to the calling function.
 Generally Output is printed in the Called function.
Example
#include<stdio.h> void
add(int x, int y); int
main()
{
add(30,15);
add(63,49);
add(952,321);
return 0;;
}
void add(int a, int b)
{
int result; result
= a+b;
} printf("Sum of %d and %d is %d\n",a,b,result);

OUTPUT

5
Sum of 30 and 15 is 45
Sum of 63 and 49 is 112
Sum of 952 and 321 is 1273

A function with arguments and returning a values


 Argument are passed by calling function to the called function
 Called function return value to the calling function
 Data returned by the function can be used later in our program for further calculation
 Mostly used in programming because it can two way communication

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

Parameter passing mechanism


There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference

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();

printf("Enter a number: ");


scanf("%d", &num);
printf("Square of %d is %d", num, square(num));

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

/* C Functins - Call by Reference Program */

#include<stdio.h>
#include<conio.h>

void swap(int *a, int *b);

void main()
{
int num1, num2;
clrscr();

printf("Enter the two number: ");


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

printf("\nValues before swapping:\n");


printf("num1 = %d \t num2 = %d\n", num1, num2);

swap(&num1, &num2); // pass the address of num1 and num2

printf("\nValues after swapping:\n");


printf("num1 = %d \t num2 = %d\n", num1, num2);

getch();
}
7
void swap(int *a, int *b)
{
int temp;

temp = *a; // save the value at address a


*a = *b;
*b = temp;

printf("\nValues in the function swap() after swapping:\n");


printf("num1 = %d \t num2 = %d\n", *a, *b);
}
Here is the sample output of the above C program:

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.

Example: C Program that calculates factorial of a given number using recursion

#include <stdio.h>

long int factorial(int);

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

Passing Arrays to functions.


Passing One-dimensional Array to a Function
Passing a single element of an array to a function is similar to passing variable to a function.

Example 1: Passing single element of an array to function

#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

Example 2: Passing an entire array to a function

// Program to calculate average by passing an array to a function


#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}
float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {

9
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Output

Average age = 27.08

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.

Passing Multi-dimensional Arrays to Function

To pass multidimensional arrays to a function, only the name of the array is passed (similar to one
dimensional array).

Example 3: Passing two-dimensional array to a function

#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]);
}

Example 1: Passing single element of an array to function

#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

Example 2: Passing an entire array to a function

// Program to calculate average by passing an array to a function


#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}
float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Output

Average age = 27.08

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.

Passing Multi-dimensional Arrays to Function

To pass multidimensional arrays to a function, only the name of the array is passed (similar to one
dimensional array).

Example 3: Passing two-dimensional array to a function

#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:

Example: Passing address to a Function

#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.

There are four storage classes in C:


1. auto
2. register
3. static
4. external

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;

 These are created when the function is called and destroyed


automatically when the function is exited.
 These variables are private (local) to the function in which they are
declared.
 Variables declared inside a function without storage class specification
is, by default, an automatic variable.

Properties of automatic variable are as under:

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;

printf ( "\n%d ", i ) ;


}
printf ( "%d ", i ) ;
}
printf ( "%d",
13
i ) ; return 0;
}

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).

Properties of external variable are as under:

Storage CPU registers


Initial value 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( )
{
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

External or Global Variables


 These variables are declared outside any function.
 These variables are active and alive throughout the entire program.
 Sometimes the keyword extern used to declare these variables.
 Unlike local variables they are accessed by any function in the
program.
 In case local and global variable have the same name, the local
variable will have precedence over the global one.
Properties of external variable are as under:

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.

Declaration and Initialization of Strings


The following declaration and initialization create a string consisting of the word "Hello".

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Another way of Initialization is (shortcut for initializing string)


char greeting[] = "Hello";

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.

Memory Representation of String


char greeting[] = "Hello";

/* Program to demonstrate printing of a string */

17
int main( )
{
char name[ ] = “CMRCET" ; int i = 0 ;
while ( i <= 9 )
{
printf ( "%c", name[i] ) ; i++ ;
}
return 0;
}

And here is the output...


CMRCET

Following program illustrates printing string using ‘\0’.


int main( )
{
char name[ ] = “CMRCET" ;
int i = 0 ;
while ( name[i] != ‘\0’ )
{
printf ( "%c", name[i] ) ;
i++ ;
}
return 0;
}

And here is the output...


CMRCET
Standard Library String Functions
With every C compiler a large set of useful string handling library
functions are provided. For using these functions, we need to include the
header file string.h

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.

Note: While calculating the length it doesn’t count ‘\0’.

Example 12: C program that illustrates the usage of strlen()


function. #include<stdio.h>

#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

The string Humpty Dumpty length is 13

strcpy( ) function
This function copies the contents of one string into another. Syntax for
strcpy() function is given below.

char * strcpy ( char * destination, const char * source );

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.

Example 13: C program that illustrates the usage of strcpy()


function. #include<stdio.h>
#include<
string.h>
int main()
{
char source[ ] =
"Sayonara" ; char
target[20]= "" ;
strcpy (destination, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s",
destination ) ; return 0;
}

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”.

Example 14: C program that illustrates the usage of strcat()


function. #include<stdio.h>

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.

If the two strings are identical, strcmp( ) returns a value zero. If


they’re not identical, it returns the numeric difference between the ASCII
values of the first non-matching pairs of characters.
Syntax for strcmp( ) function is given below.
int strcmp ( const char * str1, const char * str2

Return Value from strcmp()


Return Value Description
0 if both strings are identical (equal)
<0 if the ASCII value of first unmatched character is less than second.
>0 if the ASCII value of first unmatched character is greater than second.

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

Example 16: Program for checking string’s palindrome property.


#include<stdio.h> #include<string.h> int main()
{
char str1[25],str2[25]; int d=0;
printf("\nEnter a string:"); gets(str1); strcpy(str2,str1); strrev(str1);
d= strcmp(str1,str2); if(d==0)
printf("\n%s is pallindrome",str2); else
printf("\n%s is not a pallindrome",str2); return 0;
}

Output:
Enter a string: madam madam is palindrome

Some other palindrome strings are: civic, dad, malayalam, mom,wow etc.

getchar() and putchar() functions


The getchar() function reads a character from the terminal and
returns it as an integer. This function reads only single character at a time.
You can use this method in the loop in case you want to read more than
one characters.

The putchar() function prints the character passed to it on the screen


and returns the same character. This function puts only single character at
a time. In case you want to display more than one characters, use
putchar() method in the loop.
#include
<stdio.h>
int
main( )
{
int ch;
printf("Enter a
character:");
ch=getchar();
put
cha
r(c
h);
ret
urn

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.

puts() and gets() functions


The gets() function reads a line or multiword string from stdin into the buffer
pointed to by s
until either a terminating newline or EOF (end of file).

The puts() function writes the string s and a trailing


newline to stdout. #include<stdio.h>
int main()
{
char
str[100];
printf("Enter
a string:");
gets( str );
puts("Hello!"
); puts(str);
return 0;
}
Output
Enter a string:
Vijayanand Ch
Hello! Vijayanand
Ch

Difference between scanf() and gets()

S.No scanf() gets()


1 It reads single word strings It reads multi-word strings
2 It stops reading characters when it It stops reading characters when it
encounters a whitespace encounters a newline or EOF
3 Example: Vijay Example: Vijayanand ch

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.

3. Differentiate between call by value and call by reference with an example?

4. I) Explain about types of parameter passing mechanisms in C.

5. II) Illustrate command line arguments with example.

6. Explain various categories of function using an example program?

7. What is recursion? Write a C program to find the factorial of a given number using recursion.

Short answers:

1. What is inter function communication.

2. What is Function? What are the types of functions?

3. Distinguish between function prototype and function definition

4. What is recurstion? What are its limitations?

5. What are the different storage classes? Write the keywords.

6. What is scope? What are the different types of scope?

7. What are the different types of functions?

8. Distinguish between automatic and static variable

24

You might also like