0% found this document useful (0 votes)
2 views68 pages

C- Strings and functions

The document provides an overview of strings in C programming, explaining their declaration, initialization, and manipulation using functions like strlen(), strcat(), and strcpy(). It also discusses user-defined and library functions, emphasizing the importance of functions in managing complex programs. Additionally, it categorizes functions based on parameters and return values, illustrating their usage with examples.

Uploaded by

sanjanashintri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views68 pages

C- Strings and functions

The document provides an overview of strings in C programming, explaining their declaration, initialization, and manipulation using functions like strlen(), strcat(), and strcpy(). It also discusses user-defined and library functions, emphasizing the importance of functions in managing complex programs. Additionally, it categorizes functions based on parameters and return values, illustrating their usage with examples.

Uploaded by

sanjanashintri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 68

Strings in C language

Strings in C
• A String in C programming is a sequence of
characters terminated with a null character
‘\0’.
• The C String is stored as an array of
characters.
• The difference between a character array
and a C string is that the string in C is
terminated with a unique character ‘\0’.
C String Declaration Syntax
• Declaring a string in C is as simple as
declaring a one-dimensional array.
• basic syntax for declaring a string:
char string_name[size];
example : char str[50]

• Null character (‘\0’) used to indicate the


termination of a string that differs strings
from normal character arrays
We can initialize a C string in 4 different ways which
are as follows:

1. Assigning a String Literal without Size


String literals can be assigned without size.
Here, the name of the string str acts as a
pointer because it is an array.

char str[] = "CPROGRAMMING";


2. Assigning a String Literal with a
Predefined Size
• String literals can be assigned with a
predefined size.
• But we should always account for one extra
space which will be assigned to the null
character.
• If we want to store a string of size n then we
should always declare a string with a size
equal to or greater than n+1.
• char str[50] = "HappyDay";
3. Assigning Character by
Character with Size
• We can also assign a string character by
character. But we should remember to set
the end character as ‘\0’ which is a null
character.
char str[14] = {
'c','p','r','o','g','r','a','m','m','i','n','g','\0'};
4. Assigning Character by
Character without Size
• We can assign character by character without
size with the NULL character at the end.
• The size of the string is determined by the
compiler automatically.

• char str[] = {
'c','p','r','o','g','r','a','m','m','i','n','g','\0'};
// C program to illustrate // displaying the length of
strings string

#include <stdio.h> printf("Length of


#include <string.h> sing str is %d", length);
int main() int length = 0;
{ length = strlen(str);
// declare and initialize string
char str[] = "Geeks"; return 0;
// print string
}
printf("%s ", str);
// displaying the length of string
printf("Length of sing str
is %d", length);
Reading values to string from
the user in runtime
// To read entire string till whitespace or
space is encountered
scanf("%s",str1);

// To read entire string till specific character


( dot . ) is encountered
scanf("%[^\.]s",str2);
// program to demonstrate reading String values from the user during run time
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10],str2[10];
printf("enter a string1 \n");
// To read entire string till whitespace or space is encountered
scanf("%s",str1);
printf("entered string is %s \n",str1);

// To read entire string till specific chareter is encountered


printf("enter a string 2 \n");
scanf("%[^\.]s",str2);
printf("entered string is %s \n",str2);
return 0; }
strlen() function in c
• The strlen() function in C calculates the
length of a given string.
• The strlen() function is defined in string.h
header file. It doesn’t count the null
character ‘\0’.
• Syntax : size_t strlen(const char* str);
// c program to demonstrate strlen() function.
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "KLEBCA"; // defining string
// getting length of str using strlen()
int length = strlen(str);
printf("Length of string is : %d", length);
return 0;
}
Length of string is : 6
Concatenate Strings

strcat() : is a string function which is used to


concatenate (combine) two strings.
Syntax : strcat( target , source );
Ex : strcat (str1 , str2);
target : is the string to which additional data will be added.
Ex: str1 is target to which source string str2 data will be
combined.
source is the string whose data will be added to target
string. ex : str2 is source whose data will be added to the
target string str1.
#include <stdio.h>
#include <string.h>
main()
{
char str1[20] = "Hello ";
char str2[] = "World!";
printf("String 1 is : %s \n", str1);
printf("String 2 is : %s \n", str2);
printf("Before concatenation String 1 is : %s \n", str1);
// Concatenate str2 to str1 (result is stored in str1)
strcat(str1, str2);
printf("After concatenation String 1 is : %s\n", str1);
}
output :
String 1 is : Hello String 2 is : World!
Before concatenation String 1 is : Hello
After concatenation String 1 is : Hello World!
Copy Strings

strcpy() : is a string function which is used to copy the


contents from one string to the other string.
Syntax : strcpy( target , source );
Ex : strcat (str1 , str2);
target : is the string to which others data will be copied.
Ex: str1 is target to which source string str2 data will be copied
over original data. here Str1 original data is changed to str2’s
data.
source is the string whose data will be copied to target
string. ex : str2 is source whose data will be copied over to the
target string str1.
#include <stdio.h>
#include <string.h>
main()
{
char str1[20] = "Hello ";
char str2[] = "World!";
printf("String 1 is : %s \n", str1);
printf("String 2 is : %s \n", str2);
printf("Before copying String 1 is : %s \n", str1);
// copies str2 to str1 (result is stored in str1)
strcpy(str1, str2);
printf("After copying String 1 is : %s\n", str1);
}
output :
String 1 is : Hello String 2 is : World!
Before copying String 1 is : Hello
After copying String 1 is : World!
converting lowercase and uppercase Strings

strlwr() : is a string function which is used to convert


the contents of given string to the lowercase.
Syntax : strlwr(string);
Ex : strlwr (str1);
here the strings original data is converted to the lower
case letters .
char str1[20] = "HELLO ";
printf("%s ", strlwr(str1)); // str1 data will be converted to the
lower case letters.
output : hello
converting lowercase and uppercase Strings

strupr() : is a string function which is used to convert


the contents of given string to the uppercase.
Syntax : strupr(string);
Ex : strupr (str1);
here the strings original data is converted to the
uppercase letters .
char str1[20] = "world ";
printf("%s ", strupr(str1)); // str1 data will be converted to the
upper case letters.
output : WORLD
converting lowercase and uppercase Strings

strupr() : is a string function which is used to convert


the contents of given string to the uppercase.
Syntax : strupr(string);
Ex : strupr (str1);
here the strings original data is converted to the
uppercase letters .
char str1[20] = "world ";
printf("%s ", strupr(str1)); // str1 data will be converted to the
upper case letters.
output : WORLD
To check wether pattern sting is available in given Strings

strstr() : is a string function which is used to check


wether given pattern is present in the string or no.
Syntax : strstr(string,patern);
Ex : strstr (str1,pat);
here we check wether the patern (pat ) is present in the
original string
char str1[50] = "Vishweshraiya"; char pat[10] = “rai”
printf("%s ", strstr(str1,pat)); // pattern data will be checked
in the string str1.
output : raiya
Functions
• The programs that we study or read from
books are very small when compared to the
programs that we write for a complex
problem.
• If the program is very big, there are too many
disadvantages:
– It is very difficult for the programmer to write a
large program
– Very difficult to identify the logical errors and
correct
– Very difficult to read and understand
– Large programs are more prone to errors .
– These disadvantages can be overcome using
functions.
What is a function?

• Definition: In C language, a large program


can be divided into a series of individual
related programs called modules.
• These modules are called functions.
• Thus a function (also called subprogram) is
a program segment that carries out some
specific and well-defined tasks.
• The functions can be developed and tested
separately.
For example,

• The function sqrt() is used to find square


root of a given number.
• The function scanf() is used to read data
from the keyboard.
• The function printf() is used to print the
result on to the display unit and so on.
• What are the different types of
functions?"
• The functions can be classified into two
categories as shown below:
Library Functions
(Built in Functions)
Functions

User Defined Functions


What are library functions?
The standard C library is a collection
various types of functions which perform
some standard/and pre-defined tasks.
• These functions which are part of the C
compiler that have been written for
general purpose are called library
functions.
• They are also called built in functions.
Examples of built in functions
• sqrt() - finds the square root of a given
number.
• sin() - computes the sine of an angle.
• cos() - computes the cosine of an angle.
• scanf() - accept the data from the
keyboard.
• printf() - send the data to output unit.
// program to demostarte liberary functions

#include <math.h>
#include <stdio.h>
int main()
{
int number, squareRoot;
printf("Enter a number: ");
scanf("%d", &number);
// computing the square root
squareRoot = sqrt(number);
printf("Square root of %d = %d", number, squareRoot);
return 0;
}
output: Enter a number: 25
Square root of 25 = 5
What are User Defined Functions?
• Definition: These functions which are written by the
programmer/user to do some specific tasks are called
user defined functions (UDFs).
Without Function With Function
#include <stdio.h>
#include <stdio.h>
void add()
int main()
{
{
int n1, n2, sum;
int n1, n2, sum;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
printf("Enter two integers: ");
// calculating sum
scanf("%d %d", &n1, &n2);
sum = n1 + n2;
printf("%d + %d = %d", n1, n2,
// calculating sum sum);
sum = n1 + n2; }
printf("%d + %d = %d", n1, 2, int main()
sum);
{
return 0;
add();
}
}
Elements of user-defined
functions
• The elements of user-defined functions
are shown below:
• Function definition: The program module
that is written to achieve a specific task is
Called function definition.
For example, consider the function shown below:
void add()
{

int n1, n2, sum;

printf("Enter two integers: ");


scanf("%d %d", &n1, &n2);

// calculating sum
sum = n1 + n2;

printf("%d + %d = %d", n1, n2,


sum);
return 0;
}
• Function declaration:

Functions are like variables.


As variables are declared before they are
used, we normally declare the functions
before they are defined and end with
semicolon.

syntax:
return_type function_name(arguments);
ex : int add(int , int ) ;
#include <stdio.h>

void add(); Function Declaration


int main()
{
add(); Function Call
}

void add()
{

int n1, n2, sum;

printf("Enter two integers: ");


scanf("%d %d", &n1, &n2); Function Definition
// calculating sum
sum = n1 + n2;

printf("%d + %d = %d", n1, n2, sum);

}
Function definition
• Definition: The program module that is
written to achieve a specific task is called
function definition. The various elements
of the function definition are shown below:
Function call:
• In general, a function call is nothing but
invoking a function at the required place in
the program.
• that is after defining a function calling it or
invoking is called as function call.
int main()
{
/* This statement transfers the
add(); control to add() function */
}
#include <stdio.h>
/* Function declarations */
int max(int n1, int n2);
int main()
{
int num1, num2, maximum, minimum;
/* Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
maximum = max(num1, num2); // Call maximum function
printf("\nMaximum = %d\n", maximum);
return 0;
}
int max(int n1, int n2)
{
if(n1>n2)
return n1;
else
return n2;
}
Formal parameters
int main()
{
int num1, num2, maximum, minimum;
int max(int n1, int n2)
printf("Enter any two numbers: "); {
scanf("%d%d", &num1, &num2);
if(n1>n2)
maximum = max(num1, num2);
return n1;
printf("\nMaximum = %d\n", else
maximum);
return 0; return n2;
} }
Actual parameters
• The variables that are used while calling the function are
called actual parameters.
• The parameters passed to function are called actual
parameters.
• Actual parameters sends values to the formal
parameters

Formal parameters are used in the function header of a


called function.
• whereas the parameters received by function are
called formal parameters.
• Formal parameters receive values from the actual
parameters.
Categories of functions
• Based on the parameters and return
value, the functions are categorized as
shown below:
• Functions with no parameters and no return values
– There is no data transfer between the calling function and called
function.

– above program that the function sum() do not receive any values
from the function main() and it does not return any value to the
function main().
• Functions with no parameters and return
values
– In this category, there is no data transfer
from the calling function to the called
function. But, there is data transfer from
called function to the calling function.
– Observe from the below program that the
function sum() do not receive any values from
the function main().
– But, it accepts data from the keyboard, find the
sum of those numbers and returns the result to
the calling function.
• Functions with parameters and no return
values
– In this category, there is data transfer from the
calling function to the called function using
parameters. But, there is no data transfer from
called function to the calling function.
• Observe from the above program that the function sum() receives two values
from the function main(), finds the sum of these numbers and display the
result there itself. The result is not passed to the calling function, but only
control is transferred.
• Functions with parameters and return
values
– In this category, there is data transfer between
the calling function and called function.
– When parameters are passed, the called
function can receive values from the calling
function. When the function returns a value,
the calling function can receive a value from
the called function.
• Observe from the above program that the function sum() receives two
values from the function main(), finds the sum of these numbers and sends
the result back to the calling function.
Passing Parameter To
Functions
1. Pass by value:
In this parameter passing method, values of actual parameters are
copied to function’s formal parameters and the two types of
parameters are stored in different memory locations.
So any changes made inside functions are not reflected in actual
parameters of the caller.
This method is also called as call by value.
#include<stdio.h> void swap(int x, int y)
void swap(int*, int*); {
int main() int t;
{ t = x;
int num1 = 10, num2 = 20; x = y;
swap(num1, num2); y = t;
printf("num1=%d num2=%d\n", num1, printf("x=%d y=%d\n", x, y);
num2);
}
return 0; }
2. Pass by reference :
Both the actual and formal parameters refer to the same
locations, so any changes made inside the function are
actually reflected in actual parameters of the caller.
This method is also called as call by reference.

#include<stdio.h> void swap(int* x, int* y)


void swap(int*, int*); {
int main() int t;
{ t = *x;
int a = 10, b = 20; *x = *y;
swap(&a, &b); *y = t;
printf("a=%d b=%d\n", a, b); printf("x=%d y=%d\n", *x, *y);
return 0; }
}
Functions with arrays
• In C We can pass array as parametrs to
functions. but the whole array cannot be passed
as an argument to a function.

• However, you can pass a pointer to an array


without an index by specifying the array’s name.

• Arrays in C are always passed to the function


as pointers pointing to the first element of the
array.
// program to find maximum of elements with functions and arrays as parameter

#include<stdio.h> void max(int array[ ] , int size)


#include<string.h> {
int max_element=array[0], j;
void max(int array[ ] , int size);
printf(" Maximum element from Array is:");
int main() for(j=0;j<size;j++)
{ {
int arr[50],i,limit; if(array[j] > max_element)
printf("enter the limit of array"); max_element= array[j];
scanf("%d",&limit); }
printf("%d \n",max);
printf("enter the elements to array");
}
for(i=0;i<limit;i++)
{ Output : enter the limit of array 5
scanf("%d",&arr[i]); enter the elements to array 8
} 7
// calling a max function with array 9
elements and limit as parameters
6
max(arr,limit); 3
return 0; Maximum element from Array is: 9
}
// program to dispaly the charecters with functions and charecter arrasy as
parameter in two different ways

#include<stdio.h> void dispaly(char array[])


#include<string.h> {
int main() int j;
{ while(array[j] !='\0')
char str1[50]="welcome"; {
char str2[50]="hello"; printf("%c",array[j]);
j++;
// calling a display function with }
charector array elements and limit }
as parameters // reference of array is taken ie base
dispaly1 (str1); address to access the enitre array
dispaly2 (str2); void dispaly2 (char *array)
return 0; {
} printf("%s" ,array);
}
// program to demonstarate inbuilt string functions using use defined function
#include<stdio.h>
#include<string.h>
void strfuns(char str1[ ] , char *str2)
{
char str3[50];
printf("string length is %d\n",strlen(str1));
printf("copied string to string3 is %s\n",strcpy(str3,str1));
printf("concatinated string3 is %s\n",strcat(str1,str2));
printf("lower case of string2 is %s\n",strlwr(str2));
printf("upper case of string1 is %s\n",strupr(str1));
printf("string2 in string1 is: %s\n",strstr(str1,str2));
}
main()
{
char str1[50]="welcome to";
char str2[30]="KLE BCA";
// calling a "strfuns" function with charector array elements and limit as parameter
strfuns(str1,str2);
}
Recursion
What is recursion?
• Definition: Recursion is a technique for
defining a problem in terms of one or more
versions of the same problem.
• A function, which contains a call to itself
again and again or a call to another function,
which eventually causes the first function to
be called, is known as a recursive function.
• In recursion, the calling function and
called function are same.
Factorial Program
• The factorial of a number n is the product
of integer values from 1 to n.
#include <stdio.h>
int fact(int);
int main()
{
int num,factorial;
printf("Enter a number to calculate it's factorial\n");
scanf("%d",&num);
factorial=fact(num);
printf("Factorial of the num(%d) = %d\n",num,factorial);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
Recursive version to compute factorial of
n
• The factorial of a number n is the product
of integer values from 1 to n.
• The recursive definition to compute n! is
shown below:
Note: Thus, it is clear from the above
computations that, the recursive solution for a
problem involves a two-way journey with a
stop at the middle:
• Decompose the problem from top to bottom
which involves reducing the problem into
smaller problems of same type
• Arrive at the solution which does not involve
any recursion (Base case)
• Compute the solution from bottom to top
using the previous solutions.
#include<stdio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
int main()
{
int num;
printf("Enter a number to calculate it's
factorial\n"); scanf("%d",&num);
printf("Factorial(%d) = %d\n",num,fact(num));
return 0;
}
a. The first time when function fact() is called, 3 is passed to n.
b. Since n is not 0, the if statement is skipped and fact() is called
again with argument n-1 i.e., 2.
c. Since n is not 0, the if statement IS skipped and fact() IS called
again with argument n-1 i.e., 1.
d. Since n is not 0, the if statement IS skipped and fact() IS called
again with argument n-I i.e., O.
e. Since n is 0, control goes previous call with value 1 and 1*1 = 1
is computed and sent to the previous point of invocation.
f. The resulting value 1is passed to the point of previous invocation
and 2* 1 = 2 is computed and sent to the previous point of
invocation.
g. The resulting value 2 is passed to the point of previous
invocation and 3*2 = 6 is computed and sent to the previous point
of invocation.
h. The resulting value 6 is passed to the point of previous
invocation and 6 is copied into variable n in the main program.

You might also like