0% found this document useful (0 votes)
0 views

Module-3 PPS(Functions & Strings)

This document provides an overview of functions and strings in C programming, detailing the importance of functions for modularity and reusability. It explains the types of functions, including built-in and user-defined functions, and outlines the basic elements and categories of user-defined functions. Additionally, it covers parameter passing methods, storage classes, recursive functions, and provides examples for various programming scenarios.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module-3 PPS(Functions & Strings)

This document provides an overview of functions and strings in C programming, detailing the importance of functions for modularity and reusability. It explains the types of functions, including built-in and user-defined functions, and outlines the basic elements and categories of user-defined functions. Additionally, it covers parameter passing methods, storage classes, recursive functions, and provides examples for various programming scenarios.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Module – 3: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.

Example: void hello( )

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:

➢ Functions support top-down modular programming.


➢ By using functions, the length of the source code decreases.
➢ Writing functions makes it easier to isolate and debug the errors.
➢ Functions allow us to reuse the code.
TYPES OF FUNCTIONS: Based on the nature of functions, they can be divided into two
categories. They are:

1) In-built functions / Predefined functions / Library functions

2) User defined functions

a) In-built functions / Predefined functions: is a function which is already written by another


developer. The users generally use these library functions in their own programs for
performing the desired task.
The predefined functions are available in the header files. So, the user has to include the
respective header file to use the predefined functions available in it.
Example: the printf function which is available in the <stdio.h> header file is used for
printing information.
Other examples of predefined functions are: scanf, strlen, strcat, sqrt, fabs etc.

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.

BASIC ELEMENTS OF USER DEFINED FUNCTION: For creating user defined


functions in C programs, we have to perform three steps. They are:

a) Function Declaration: Declaring the function (blue-print).

b) Function Definition: Defining the function (logic).

c) Function Calling: use of function in program (calling)


a) FUNCTION DECLARATION: The function declaration is the blue print of the function.
The function declaration can also be called as the function’s prototype.
The function declaration tells the compiler and the user about what is the function’s name,
inputs and output(s) of the function and the return type of the function.
Syntax: for declaring a function is shown below:
return_type function_name(parameters list);
Example:
int add(int m, int n);
In the above example, add is the name of the function, int is the return type of the function.
In our example, add function has two parameters. The parameters list is optional.

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

b) function without arguments and with return value

c) function with arguments and without return value

d) function with arguments and with return value

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

In C, there are two types of parameters and they are as follows:


There are two methods to pass parameters from calling function to called function:

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.

example: static int i=1;


Global static variables can be accessed anywhere in the program. By default, they are
assigned the value 0 by the compiler.

• “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.

• FACTORIAL OF A NUMBER – Factorial of n is the product of all positive descending


integers. Factorial of n is denoted by n!
Example: 5! = 5*4*3*2*1 = 120
Recursive Function:
5! = 5 * 4! // n * Fact(n-1)
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1 * 0!
0! = 1 //Stop Condition

Program to find factorial of given number using recursive function:


#include<stdio.h>
int fact(int);
void main()
{
int n, res;
printf("Enter any integer number: ");
scanf("%d",&n);
res =fact(num);
printf("factorial is %d",res);
}
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*fact(n-1));
}
}
• FIBONACCI SERIES – a series of numbers in which each number ( Fibonacci number ) is
the sum of the two preceding numbers.
Example: 0, 1, 1, 2, 3, 5, 8, etc.
The first two numbers of fibonacci series are 0 and 1.

Recursive Function: There are 3 cases in fibonacci series


1) if n = 1 only one digit to be printed i.e “0”.
2) if n = 2 only two digit to be printed i.e “1”.
3) if n > 2 last two digits to be added & printed so “fib(n-1) + fib(n-2)”

Program to find Fibonacci Series using recursive function:


#include<stdio.h>
int fib(int);
void main()
{
int n, i = 0, c;
printf(“enter N value: ”);
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fib(i));
i++;
}
}
int fib(int n)
{
if (n == 0 || n == 1)
{
return n;
}
else
{
return (fib(n-1) + fib(n-2));
}
}
OTHER EXAMPLE PROGRAMS TO BE PREPARED FROM FUNCTIONS:

• Program to Convert Binary number to Decimal using Recursive Function:


#include <stdio.h>
int convert(int);
void main()
{
int dec, bin;
printf("Enter a Binary number: ");
scanf("%d", &bin);
dec = convert(bin);
printf("Equivalent decimal value is %d”,dec);
}
int convert(int bin)
{
if (bin == 0)
{
return 0;
}
else
{
return (bin % 10 + 2 * convert(bin/10));
}
}

• Program to multiply the given two matrices using functions:

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

• Some of the examples of string constants are:


1)“hai”
2)“hello world”
3)“My name is NITHIN”
In C programming, there is no predefined data type to declare and use strings. So, we use
character arrays to declare strings in C programs.
Example: char s[5];

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

• Syntax for formatted input/output:


1) Read – char str[10];
scanf(“%s”, str);
2) Print – printf(“The string is %s”, str);

• Syntax for unformatted input/output:


1) Read – char str[10];
gets(str); //gets(string_name);
2) Print – printf(“The string is:”);
puts(str); //puts(string_name);

• Example C program to Read & Print Strings:


/*Using scanf & printf*/

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

STRING-MANIPULATION FUNCTIONS(Built-in String Functions): C provides


predefined functions for performing all operations or manipulations on strings. Most of these
predefined functions are available in string.h header file. The list of predefined functions is
given below:

1) String-concatenate (strcat): The strcat predefined function is used to concatenate/join


two strings together. The syntax of the strcat function is shown below:
strcat(string1,string2);

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:

3) String-compare(strcmp): The strcmp predefined function is used to compare two


strings. The syntax of strcmp function is as shown below:
strcmp(string1,string2);
After comparison:
1) If the two strings are equal, then the function returns a 0.
2) If 1st string is greater than 2nd string returns > 0.
3) If 1st string is lesser than 2nd string returns < 0.
Example:
4) String-copy (strcpy): The strcpy function is used to copy one string into another string.
This function can be used for creating a copy of an existing string. The syntax
of strcpy function is as shown below:
strcpy(string1,string2);

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

You might also like