0% found this document useful (0 votes)
4 views26 pages

Unit 4

This document provides an overview of functions in C programming, including definitions, types (built-in and user-defined), and the structure of function declarations, definitions, and calls. It categorizes functions based on their arguments and return values, explains parameter passing methods (call by value and call by reference), and discusses variable scope (local, global, and formal parameters). Additionally, it emphasizes the importance of initializing variables and demonstrates how to pass pointers as function arguments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

Unit 4

This document provides an overview of functions in C programming, including definitions, types (built-in and user-defined), and the structure of function declarations, definitions, and calls. It categorizes functions based on their arguments and return values, explains parameter passing methods (call by value and call by reference), and discusses variable scope (local, global, and formal parameters). Additionally, it emphasizes the importance of initializing variables and demonstrates how to pass pointers as function arguments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT 4

FUNCTIONS AND STRINGS


INTRODUCTION

DEFINITION OF FUNCTION:
A function is a set of statements that take inputs, do some specific computation and produces
output. A function is a group of statements that together perform a task.
The idea is to put some commonly or repeatedly done task together and make a function so that
instead of writing the same code again and again for different inputs
Every C program has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.

In the C programming language, the function is divided into two parts: the built-in/ library function
and the user-defined function.

Library/ Built-in Function

A library function is predefined functions, and its tasks are also defined in the C header files. So, it
does not require writing the code of the particular function; instead, it can be called directly in a
program whenever it is required.

Example: printf(), scanf(), getch(), etc., are the predefined function in the C library, and the meaning
of these functions cannot be changed.

User-defined Function

It is a user-defined function in the C programming language to execute some specific actions


according to the programmer's requirement.

A user-defined function is divided into three types such as


• Function Declaration
• Function Definition
• Function Call.

Function Declaration

A function declaration defines the name and return type of a function in a program. Before using the
function, we need to declare it outside of a main() function in a program.

Syntax:
return_data_type function_name ( data_type arguments) ;

Example of function declaration:


int add ( int num1, int num2 );
In the above example, int is a return data type of the function name add function that contains two
integer parameters as num1 and num2. Furthermore, we can write the above function declaration is
as follows:
int add (int, int);

Function Definition

It defines the actual body of a function inside a program for executing their tasks in C.

Syntax:

return_data_type function_name (argument list )


{
// Statement to be executed in a function;
}

In the above syntax, a function definition contains the three parts as follow:

1. Return Data_Type: It defines the return data type of a value in the function. The return data
type can be integer, float, character, etc.
2. Function Name: It defines the actual name of a function that contains some parameters.
3. Parameters/ Arguments: It is a parameter that passed inside the function name of a
program. Parameters can be any type, order, and the number of parameters.
4. Function Body: It is the collection of the statements to be executed for performing the
specific tasks in a function.

Consider an example to demonstrate the function definition:

int min (int n1, int n2); // min() is the name of a function that contains n1 and n2 parameters
{
// declaration of the local variable.
int out;
if ( n1 > n2)
out = n1; // return n1 when n1 is greater than n2.
else
out = n2; // return n2 when n2 is greater than n1.
return out;
}
Function Calling:
A function call is an important part of the C programming language. It is called inside a program
whenever it is required to call a function. It is only called by its name in the main() function of a
program. We can pass the parameters to a function calling in the main() function.
Syntax:

Add(a, b) // a and b are the parameters

Let's consider a program to call a function in C programming languages.

Add.c

#include <stdio.h>
int add(int a, int b);
void main()
{
int sum;
int a, b;
printf(" Enter the first and second number \n");
scanf("%d %d", &a, &b);
sum = add(a, b); // call add() function
printf( "The sum of the two number is %d", sum);
}
int add(int n1, int n2) // pass n1 and n2 parameter
{
int c;
c = n1 + n2;
return c;
}

Output:

Enter the first and second number


5
6
The sum of the two number is 11

CATEGORIES OF FUNCTIONS
Depending on whether arguments are present or not and whether a value is returned or not, functions
are categorized into −

• Functions without arguments and without return values


• Functions without arguments and with return values
• Functions with arguments and without return values
• Functions with arguments and with return values
1. Functions without arguments and without return values
There is no data transfer between the calling function and the called function in the category function
without arguments and without a return value.

Example:
#include<stdio.h>
main ()
{
void sum ();
clrscr ();
sum ();
}
void sum ()
{
int a,b,c;
printf("enter 2 numbers:\n");
scanf ("%d%d", &a, &b);
c = a+b;
printf("sum = %d",c);
}
Output:
Enter 2 numbers:
3
5
Sum=8

2. Functions without arguments and with return values


When a function has no arguments, it does not receive any data from the calling function. When a
function returns a value, the calling function receives data from the called function.
Example:
#include<stdio.h>
main ()
{
int sum ();
int c;
c= sum ();
printf(“sum = %d”,c);
}
int sum ()
{
int a,b,c;
printf(“enter 2 numbers”);
scanf (“%d%d”, &a, &b);
c = a+b;
return c;
}
Output: Enter two numbers 10 20
30

3. Functions with arguments and without return values


When a function definition has arguments, it receives data from the calling function.The actual
arguments in the function call must correspond to the formal parameters in the function definition,
i.e. the number of actual arguments must be the same as the number of formal parameters, and each
actual argument must be of the same data type as its corresponding formal parameter.
Example:
#include<stdio.h>
main ()
{
void sum (int, int );
int a,b;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
sum (a,b);
}
void sum ( int a, int b){
int c;
c= a+b;
printf (“sum=%d”, c);
}
Output
Enter two numbers 10 20
Sum=30

Functions with arguments and with return values


When a function definition has arguments, it receives data from the calling function. After taking
some desired action, only one value will be returned from called function to the calling a
function through the return statement.
If a function returns a value, the function call may appear in any expression, and the returned value
used as an operand in the evaluation of the expression.

Example
#include<stdio.h>
int sum ( int,int);
main ()
{
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
}
int sum ( int a, int b )
{
int c;
c= a+b;
return c;
}
Output
Enter two numbers 10 20
Sum=30

Passing parameters to Functions:


When a function is called, the calling function has to pass some values to the called functions.
There are two ways by which we can pass the parameters to the functions:
1. Call by value
• Here the values of the variables are passed by the calling function to the called function.
• If any value of the parameter in the called function has to be modified the change will be
reflected only in the called function.
• This happens as all the changes are made on the copy of the variables and not on the actual
ones.
Example: Call by value

#include <stdio.h>
int sum (int n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
a = sum(a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int n)
{
n = n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
return n;
}

Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = 25
The value of 'a' after calling the function is = 25
2. Call by reference
• Here, the address of the variables are passed by the calling function to the called function.
• The address which is used inside the function is used to access the actual argument used in
the call.
• If there are any changes made in the parameters, they affect the passed argument.
•For passing a value to the reference, the argument pointers are passed to the functions just
like any other value.
Example: Call by reference

#include <stdio.h>
int sum (int *n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
sum(&a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int *n)
{
*n = *n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
}
Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = -1079041764
The value of 'a' after calling the function is = 25

Comparison between call by value and call by reference:

S. No. Key Call by Value Call by Reference

Naming As in this type the value of On other hand in this type the reference
1 Convention parameter is get passed for of parameter is get passed for invoking
function invocation hence it the function so it is named as Call by
is named as Call by Value. Reference.

Internal In Call by value the value of In Call by reference the location


implementati parameter we passed during address/reference of passed parameter is
2 on calling of function are get get copied and assigned to the local
copied to the actual local argument of the function so both passed
argument of the function. parameter and actual argument refers to
the same location.

Effects of As value of passed As both argument and passed parameter


changes parameter is copied to refers to the same location hence any
argument of function so any change done to argument inside the
3
change done in argument function get reflected in the passed
inside the function do not parameter.
get reflected in the passed
parameter.

Referred Memory location referred Memory location referred by both passed


4
Memory both passed parameter and parameter and actual argument of
actual arguments of function
S. No. Key Call by Value Call by Reference

location is different. function is same.

Supported Call by value is get Call by reference is primarily get


5 languages. supported by languages such supported by JAVA.
as : C++.PHP. Visual Basic
NET, and C#.

Scope of a Variable:

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables can
be declared in C programming language −
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.
• In the definition of function parameters which are called formal parameters.

Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.

#include <stdio.h>
int main ()
{
/* local variable declaration */ int a, b;
int c;
/* actual initialization */ a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of
the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.
#include <stdio.h>
/* global variable declaration */ int g;
int main ()
{
/* local variable declaration */ int a, b;
/* actual initialization */ a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0;
}

A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example –
#include <stdio.h>

/* global variable declaration */


int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result –

value of g = 10

Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result –

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it yourself.
Global variables are initialized automatically by the system when you define them as follows −

Data Type Initial Default Value

Int 0

Char '\0'

Float 0

Double 0

Pointer NULL

It is a good programming practice to initialize variables properly, otherwise your program may
produce unexpected results, because uninitialized variables will take some garbage value already
available at their memory location.

Passing pointers as an function arguments:


C programming allows passing a pointer to a function. To do so, simply declare the
function parameter as a pointer type.
Following is a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function −
Example:

#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10
CommandLine Arguments:
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important for
your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to
the program. Following is a simple example which checks if there is any argument supplied from
the command line and take action accordingly –
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing

When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.

When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected

It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the
first command line argument supplied, and *argv[n] is the last argument. If no arguments are
supplied, argc will be one, and if you pass one argument then argc is set at 2.

You pass all the command line arguments separated by a space, but if argument itself has a space
then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us
re-write above example once again where we will print program name and we also pass a command
line argument by putting inside double quotes −

#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}

When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
$./a.out "testing1 testing2"

Program name ./a.out


The argument supplied is testing1 testing2

Passing Arrays as Function Arguments:


If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received.
Similarly, you can pass multi-dimensional arrays as formal parameters.
Way-1
Formal parameters as a pointer –
void myFunction(int *param) {
.
.
.
}
Way-2
Formal parameters as a sized array –
void myFunction(int param[10]) {
.
.
.
}
Way-3
Formal parameters as an unsized array –
void myFunction(int param[]) {
.
.
.
}
Example
Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed through
the array as follows −
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now, let us call the above function as follows –
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
When the above code is compiled together and executed, it produces the following result −
average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for formal parameters.
Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
Program. They precede the type that they modify. We have four different storage classes in a C
program −
• auto
• register
• static
• extern
1. The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.
2. The register Storage Class
The register storage class is used to define local variables that should be stored in a register instead
of RAM. This means that the variable has a maximum size equal to the register size (usually one
word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should
also be noted that defining 'register' does not mean that the variable will be stored in a register. It
means that it MIGHT be stored in a register depending on hardware and implementation
restrictions.
3. The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of
scope. Therefore, making local variables static allows them to maintain their values between
function calls.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member
to be shared by all the objects of its class.

#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

When the above code is compiled and executed, it produces the following result
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

4. The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized however, it points the variable
name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.

First File: main.c


#include <stdio.h>
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}

Second File: support.c


#include <stdio.h>
extern int count;
void write_extern(void)
{
printf("count is %d\n", count);
}

Here, extern is being used to declare count in the second file, where as it has its definition in the first
file, main.c. Now, compile these two files as follows −

$gcc main.c support.c

It will produce the executable program a.out. When this program is executed, it produces the
following result −

count is 5

Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a


program allows you to call a function inside the same function, then it is called a recursive call of the
function.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it
will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.

Example: Refer Fibonacci and factorial in observation book


Strings:

Definition:
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". 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 "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C−

Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
the above mentioned string −

#include <stdio.h> int

main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message:
%s\n", greeting ); return 0;
}

When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
String processing with and without functions:

C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose

strcpy(s1, s2); Copies string s2 into string s1.


1
strcat(s1, s2); Concatenates string s2 onto the end of string s1.
2
strlen(s1); Returns the length of string s1.
3
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
4
than 0 if s1>s2.
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string
5
s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
6
The following example uses some of the above-mentioned functions –
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

When the above code is compiled and executed, it produces the following result −

strcpy( str3, str1) : Hello strcat( str1, str2):


HelloWorld strlen(str1) :
10

Examples: Refer observation for programs with out using built-in functions
String Library functions
The predefined functions which are designed to handle strings are available in the library “string.h”.
They are −
• strlen ()
• strcmp ()
• strcpy ()
• strncmp ()
• strncpy ()
• strrev ()
• strcat ()
• strstr ()
• strncat ()

The strlen () function


It returns the number of characters in a string.
Syntax
int strlen (string name)
Example
#include <string.h>
main (){
char a[30] = “Hello”;
int l;
l = strlen (a);
printf (“length of the string = %d”, l);
}
Output
length of the string = 5
The strcpy () function
• It is for copying source string into destination string.
• The length of the destination string >= source string.
Syntax
strcpy (Destination string, Source String);
For example,
1) char a[50];
strcpy (“Hello”,a);
o/p: error
2) char a[50];
strcpy ( a,”hello”);
o/p: a= “Hello”
Example
#include <string.h>
main ()
{
char a[50], b[50];
printf ("enter a source string");
scanf("%s", a);
printf("enter destination string");
scanf("%s",b);
strcpy ( b,a);
printf ("copied string = %s",b);
}
Output
Enter a source string : Hello
Copied string = Hello

The strncpy () function


• It copy’s ‘n’ characters of source string into destination string.
• The length of the destination string must >= that of the source string.
Syntax
strncpy (Destination string, Source String, n);
Example
#include<string.h>
main ()
{
char a[50], b[50];
printf ("enter a string");
gets (a);
gets(b);
strncpy (b,a,3);// copy first 3 char from a string
b[3] = '\0';
printf ("copied string = %s",b);
}
Output
Enter a string : Hello
Copied string = Hel
It is also used for extracting substrings;
The strcat () function
• It combines two strings.
• The length of the destination string must be > than the source string.
Syntax
strcat (Destination String, Source string);
Example
#include <string.h>
main(){
char a[50] = "Hello";
char b[20] = "Good Morning";
strcat (a,b);
printf("concatenated string = %s", a);
}
Output
Concatenated string = Hello Good Morning
The strncat () function
• This is used for combining or concatenating n characters of one string into another.
• The length of the destination string must be greater than the source string
• The resultant concatenated string will be in the destination string.
Syntax
strncat (Destination String, Source string,n);
Example
#include <string.h>
main ()
{
char a [30] = "Hello";
char b [20] = "Good Morning";
clrscr ();
strncat (a,b,4);
a [9] = '\0';
printf("concatenated string = %s", a);
}
Output
Concatenated string = Hello Good.
The strcmp() function (String comparison)
• This function compares 2 strings.
• It returns the ASCII difference of the first two non – matching characters in both the strings.
Syntax
int strcmp (string1, string2);
//If the difference is equal to zero, then string1 = string2
//If the difference is positive, then string1 > string2
//If the difference is negative, then string1 < string2
Example
#include<stdio.h>
#include<string.h>
int main ()
{
char a[50], b [50];
int d;
printf ("Enter 2 strings:");
scanf ("%s %s", a,b);
d = strcmp(a,b);
if (d==0)
{
printf("%s is (alphabetically) equal to %s", a,b);
}else if (d>0)
{
printf("%s is (alphabetically) greater than %s",a,b);
}else if (d<0)
{
printf("%s is (alphabetically) less than %s", a,b);
}
}
Output
Enter 2 strings:apple ball
apple is (alphabetically) less than ball
The strncmp () function
This function is used for comparing first ‘n’ characters of 2 strings.
Syntax
strncmp ( string1, string2,2)
For example, char a[10] = “the”;
char b[10] = “there”
strncmp (a,b,4);
Output − Both strings are equal
The strrev() function
• The function is used for reversing a string.
• The reversed string will be stored in the same string.
Syntax
strrev (string)
Example
#include<stdio.h>
main (){
char a[50] ;
clrscr();
printf ("enter a string");
gets (a);
strrev (a);
printf("reversed string = %s",a)
}
Output
enter a string Hello
reversed string = olleH
The strstr() function
• It is used to search whether a substring is present in the main string or not.
• It returns pointer to first occurrence of s2 in s1.
Syntax
strstr(mainsring,substring);
Example
#include<stdio.h>
void main()
{
char a[30],b[30];
char *found;
printf("Enter a string:\t");
gets(a);
printf("Enter the string to be searched for:\t");
gets(b);
found=strstr(a,b);
if(found)
printf("%s is found in %s in %d position",b,a,found-a);
else
printf("-1 since the string is not found");
}
Output
Enter a string: how are you
Enter the string to be searched for: you
you is found in 8 position

POINTERS AND STRINGS

The variable name of the string str holds the address of the first element of the array i.e., it points at
the starting memory address.

So, we can create a character pointer ptr and store the address of the string str variable in it. This
way, ptr will point at the string str.

In the following code we are assigning the address of the string str to the pointer ptr.

char *ptr = str;

We can represent the character pointer variable ptr as follows.


The pointer variable ptr is allocated memory address 8000 and it holds the address of the string
variable str i.e., 1000.

Accessing string via pointer

To access and print the elements of the string we can use a loop and check for the \0 null character.

In the following example we are using while loop to print the characters of the string variable str.

#include <stdio.h>
int main(void)
{
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0')
{
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++;
}
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy