Module-3 PPS(Functions & Strings)
Module-3 PPS(Functions & Strings)
FUNCTIONS: “In c, we can divide a large program into the basic building blocks known
as function. The function contains the set of programming statements enclosed by {} that
performs a particular task/job”.
A function can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program. The function is also
known as procedure or subroutine in other programming languages.
printf("hello nithin");
Need of Functions: Until now, in all the C programs that we have written, the program consists
of a main function and inside that we are writing the logic of the program.
The disadvantage of this method is, if the logic/code in the main function becomes huge or
complex, it will become difficult to debug the program or test the program or maintain the
program. So we’ll break down entire logic into different parts, this type of approach for solving
the given problems is known as Top Down approach.
Advantages of Functions: Functions have many advantages in programming. Almost all the
languages support the concept of functions in some way. Some of the advantages of
writing/using functions are:
b) User defined functions: A user defined function is a function which is declared and defined
by the user himself. While writing programs, if there are no available library functions for
performing a particular task, we write our own function to perform that task.
Example: for user defined function is main function.
b) FUNCTION DEFINITION: The function definition specifies how the function will be
working i.e the logic of the function will be specified in this step.
Syntax: of function definition is shown below
return_type function_name(parameters list)
{
local variable declaration's;
---
return(expression);
}
Example:
int add(int a, int b)
{
int res;
res = a+b;
return res;
}
c) FUNCTION CALLING: After declaring and defining the functions, we can use the
functions in our program. For using the functions, we must call the function by its name.
Syntax: of function definition is shown below
function_name(parameters list);
Example: add(m,n);
Whenever the compiler comes across a function call, it takes the control of execution to the
first statement in the function’s definition. After the completion of function i.e., whenever the
compiler comes across the return statement or the closing brace of the function’s body, the
control will return back to the next statement after the function call.
CATEGORIES OF USER DEFINED FUNCTIONS: 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.
a) Function without arguments and without return value: In this type of functions there are
no parameters/arguments in the function definition and the function does not return any value
back to the calling function.
Generally, these types of functions are used to perform housekeeping tasks such as printing
some characters etc.
Example:
#include<stdio.h>
void add( );
void main( )
{
add( );
}
void add( )
{
int a, b, res;
printf(“Enter two numbers:\n”);
scanf(“%d %d”, &a, &b);
res=a+b;
printf(“Result is %d”, res);
}
In the above example, add function does not have any parameters. Its task is to read two
numbers & print the result whenever it is called in a program.
b) Function without arguments and with return value: In this type of functions, the function
definition does not contain arguments. But the function returns a value back to the point at
which it was called.
Example:
#include<stdio.h>
int add( );
void main( )
{
res=add( );
printf(“result is %d”,res);
}
int add( )
{
int a,b, res;
printf(“Enter two number: “);
scanf(“%d %d”,&a, &b);
res=a+b;
return res;
}
In the above example, add function has no parameters/arguments. The task of this function is
to read two integer from the keyboard and return back result to the point at which the
function was called.
c) Function with arguments and without return value: In this type of functions, the function
definition contains arguments. But the function does not returns a value back to the point at
which it was called.
Example:
#include<stdio.h>
void add(int,int);
void main( )
{
int a,b;
printf(“Enter a and b values: ”);
scanf(“%d %d”,&a, &b);
add(a,b);
}
void add(int a, int b)
{
int res;
res=a+b;
printf("Result is %d",res);
}
In the above example, add function has two parameters/arguments. The task of this function
is to print the sum without using return value.
d) Function with arguments and with return value: In this type of functions, the function
definition consists of parameters/arguments. Also, these functions returns a value back to the
point at which the function was called. These types of functions are the most frequently used
in programming.
Example:
#include<stdio.h>
int add(int, int);
void main( )
{
int a, b;
printf(“Enter the values of a and b: ”);
scanf(“%d %d”, &a, &b);
res=add(a,b);
printf(“result is %d”,res);
}
int add(int a, int b)
{
int res;
res = a + b;
return res;
}
In the above example, the function add consists of two arguments or parameters x and y. The
function adds both x and y and returns that value stored in the local variable result back to
the point at which the function was called.
NESTED FUNCTION: A function calling another function within its function definition is
known as a nested function.
So, far we are declaring a main function and calling other user-defined functions and predefined
functions like printf, scanf, gets, puts etc., So, main function can be treated as a nested
function.
Example:
void main()
{
func1();
}
void func1()
{
for(i=1;i<10;i++)
{
func2();
}
}
void func2()
{
printf(“%d\n”,i);
}
PARAMETERS PASSING IN C FUNCTION: 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. In C, there are two
types of parameters and they are as follows:
1) Actual Parameters
2) Formal Parameters
There are two methods to pass parameters from calling function to called function and they are
as follows...
1) Pass by Value
2) Pass by Reference
a) PASS 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 does 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.
Example: Program to swap two numbers using pass by value
#include<stdio.h>
void swap(int, int);
void main( )
{
int a,b;
printf(“Enter two numbers: ”);
scanf(“%d %d”, &a, &b);
swap(a,b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(“A is %d\t B is %d”,a,b);
}
b) PASS BY REFERENCE: In Call by Reference parameter passing method, the memory
location address of the actual parameters is copied to formal parameters. This address is used
to access the memory locations of the actual parameters in called function.
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.
Example: Program to swap two numbers using pass by reference(pointer)
#include<stdio.h>
void swap(int *, int *);
void main( )
{
int a,b;
printf(“Enter two numbers: ”);
scanf(“%d %d”, &a, &b);
swap(&a,&b);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(“A is %d\t B is %d”,*a,*b);
}
SCOPE, VISIBILITY & LIFETIME OF VARIABLES (STORAGE CLASSES)
• “auto” This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared and
not outside them (which defines their scope).
example: auto int i=1;
They are assigned a garbage value by default whenever they are declared.
• “extern” extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used.
The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program.
example: int i=1;---------→ extern int i;
a normal global variable can be made extern as well by placing the ‘extern’ keyword before
its declaration/definition in any function/block.
• “static” This storage class is used to declare static variables which are popularly used while
writing programs in C language.
Static variables have a property of preserving their value even after they are out of their
scope! Hence, static variables preserve the value of their last use in their scope.
• “register” This storage class declares register variables which have the same functionality as
that of the auto variables.
The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of register variables to be
much faster than that of the variables stored in the memory during the runtime of the
program.
example: register int i;
An important and interesting point to be noted here is that we cannot obtain the address of a
register variable using pointers.
RECURSIVE FUNCTION: A function is said to be recursive, if a function calls itself
within the function’s definition.
When writing recursive functions, proper care must be taken that the recursive calls return a
value back at some point. Otherwise, the function calls itself infinite number of times.
Example:
In the above example, func1 is calling itself in the last line of its definition.
#include<stdio.h>
void multiply(int mat1[10][10],int mat2[10][10],int ,int ,int, int);
void main()
{
int mat1[10][10],mat2[10][10],i,j,k,m,n,p,q;
printf("Enter the number of rows and columns for 1st matrix\n");
scanf("%d%d",&m,&n);
printf("Enter the number of columns & rows for 2nd matrix\n");
scanf("%d %d",&p, &q);
if(n!=p)
{
printf("Multiplication not possible");
}
else
{
printf("Enter the elements of the mat1\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("Enter the elements of the mat2\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&mat2[i][j]);
}
}
multiply(mat1,mat2,m,n,p,q);
}
}
void multiply(int mat1[10][10],int mat2[10][10],int m,int n,int p, int q)
{
int mul[10][10],i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
mul[i][j]=0;
for(k=0;k<p;k++)
{
mul[i][j]=mul[i][j]+mat1[i][k]*mat2[k][j];
}
}
}
printf("The resultant matrix formed on multiplying the two matrices\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
STRINGS: A string is a sequence of characters terminated with a null character \0. A group of
characters enclosed in double quotes is known as a string constant.
a) String Declaration & Initialization: we should declare strings before using them in
the program. Strings are implemented as character arrays.
Syntax: char string_name[size];
Example: char student_name[26];
When the compiler assigns a character string to a character array, it appends a ‘\0’ to the end of
the array. So, the size of the character array should always be number of characters plus 1.
Character arrays can also be initialized when they are declared. Some of the examples for
initializing the string are as shown below:
1) char name[13] = {‘N’,’I’,’T’,’H’,’I’,’N’,’’,’K’,’U’,’M’,’A’,’R’,’\0’};
2) char name[13] = “NITHIN KUMAR”;
If less number of characters are provided than the size of the string, the rest of the characters are
initialized to ‘\0’.
b) Reading & Writing Strings: There are two ways read & write the strings
1) Formatted input/output – scanf & printf
2) Unformatted input/output – gets & puts
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}
/*Using gets & puts*/
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
gets(name);
printf("Name: ");
puts(name);
}
The strcat function accepts two parameters which are strings. The strcat function takes the
content of string2 and merges it with the content in string1 and the final result will be stored
in string1.
Example:
2) String-length (strlen): The strlen function is used to retrieve the length of a given
string. The return type of this function will be an integer. The syntax of strlen function is as
shown below:
strlen(string);
The function returns the length of the string which will be the number of characters in the string
excluding the ‘\0’ character.
Example:
The string in string2 is copied into string1 and the result will be stored in string1
Example:
5) String-reverse (strrev): The strrev function is used to reverse a given string. We can
use this predefined function to check whether a given string is a palindrome or not. The
syntax for using the strrev function is as shown below:
strrev(string);
the strrev function reverses the given string and returns it back. The content of the string also
changes.
Example:
EXAMPLE PROGRAMS TO BE PREPARED FROM STRINGS:
• C program to find whether the given string is palindrome or not.
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, len, flag;
flag = 0;
printf("Enter any String : ");
scanf(“%s”, str);
len = strlen(str);
for(i = 0; i < len; i++)
{
if(str[i] != str[len - i - 1])
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("String is a Palindrome String");
}
else
{
printf("String is Not a Palindrome String");
}
}
• C program to print String Length without Built-in function
#include<stdio.h>
#include<string.h>
int my_strlen(char[]);
void main()
{
int len;
char str[26]];
printf("Enter String:");
scanf("%s",str);
len=my_strlen(str);
printf("Length is %d",len);
}
int my_strlen(char str1[])
{
int i=0;
while(str1[i] != '\0')
{
i++;
}
return i;
}
• C program to Compare two String’s without Built-in function
#include<stdio.h>
#include<string.h>
int my_strcmp(char[],char[]);
void main()
{
int comp;
char str1[26], char str2[26];
printf("Enter Strings:");
scanf("%s %s",str1,str2);
comp=my_strcmp(str1,str2);
if(comp==0)
{
printf("Both are equal");
}
else if(comp>0)
{
printf(“String-1 is greater”);
}
else
{
printf(“String-2 is greater”);
}
int my_strcmp(char str1[],char str2[])
{
int i=0;
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
{
break;
}
i++;
}
return str1[i]-str2[i];
}
• C program to concate two String’s without Built-in function
#include<stdio.h>
#include<string.h>
void my_concat(char[],char[]);
void main()
{
int comp;
char str1[26], char str2[26];
printf("Enter Strings: ");
scanf("%s %s",str1,str2);
my_concat(str1,str2);
void my_concat(char str1[],char str2[])
{
int i=0,j=0;
while(str1[i]!='\0')
{
i++;
}
while(str2[j]!='\0')
{
str1[i++]=str2[j++];
}
str1[i]='\0';
printf("Concatenated string is %s",str1);
}