0% found this document useful (0 votes)
8 views33 pages

P&DS Unit3 Theory

This document covers the fundamentals of functions in C programming, including function declaration, definition, and calling methods. It explains the differences between built-in and user-defined functions, as well as the concepts of call by value and call by reference. Additionally, it provides examples of various function types and their usage in structured programming to enhance modularity and code reusability.

Uploaded by

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

P&DS Unit3 Theory

This document covers the fundamentals of functions in C programming, including function declaration, definition, and calling methods. It explains the differences between built-in and user-defined functions, as well as the concepts of call by value and call by reference. Additionally, it provides examples of various function types and their usage in structured programming to enhance modularity and code reusability.

Uploaded by

Dinesh Katepalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-3

P&DS
FUNCTIONS

Syllabus:

 Function declaration
 Function definition
 Function call
 Call by value
 Call by reference
 Recursion
 String Fundamentals
 String Handling Functions
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 {}. 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 procedureor subroutinein other programming languages.

Function is a part of program which consists of group of instructions to perform


a specific task.

Designing Structured Programs:-


The structured programming approach helps to solve the large problems easily by
breaking them in to small problems. The following steps are used in structured programming
approach to design a program.
1. To solve a large problem, break the problem into several small sub problems and
work on each problem separately.
2. To solve each sub problem, treat it as a new problem that can itself be broken
down into smallerproblems.
3. Repeat the process with each new sub problem until each can be solved
independentl y, without furtherdecomposition.
 FunctionBasics:-
In C, each sub problem or module is implemented as function. Therefore, we can
define function as the block of the code which performs/ executes a specific task.
The following are the advantages of the functions.
4. Easy to implement andupdate.
5. Easy to read andunderstand.
6. Easy todebug.
7. Modularity can be achieved – Divides the large program in to smallones.
8. Codereusability.
9. Reduces the code duplication(redundancy).
10. Length of the program can bereduced.

In C, there are two types of functions namely as follows.


1. [Link](Library function) or
2. User definedfunctions.
 Libraryorbuilt-infunctions
 User-definedfunctions

Functions

Predefined Userdefined
Usercustomized
Libraryfunctions Functions, to
reduceComplexityofbi
g
Declarationinheaderfiles.

[Link]

3.
Built-in functions are also called as library function or pre-defined functions or
standard functions. These functions are available in C header files. scanf(), printf(),
strlen() etc. are some of the examples for built-in functions.
User defined functions are the functions which are developed by users/programmers.
The C program contains at least one function [Link](). The program execution starts
from main().
The following information should be known before entering in to the functions.
Return type: It says about the type of data that can be returned from the function after
execution. Return type can be of any data type such as int, double, char, void, short etc.
Function name: It is an identifier. It identifies the function with unique name which
given by the programmer. However it is advised to have a meaningful name for the
functions so that it would be easy to understand the purpose of function just by seeing
its name.

Argument/Parameter list: Argument list contains variables names along with their
data types. These arguments are kind of inputs for the function. For example – A
function which is used to add two integer variables will be having two integer
arguments. Arguments are of two types namely actual arguments and formal
arguments.
Called function: the function which is called by another function to execute is known
as called function.
Calling function: the function which calls another function to execute is known as
calling function.
In C, each function should consist of following components
 Function declaration or functionprototype
 Functiondefinition
 Functioncall

User DefinedFunctions:-
These are the functions which are developed by the user/programmer according to their
program requirements.

Function declaration:-
Each and every function should be declared before they used. Function prototype /
declaration gives compiler information about function name, type of arguments to be passed
and returntype.

Syntax:
<Return data type><Function name> (<datatype><var1>, <datatype><var2>,...);

Note: function prototype can skip, if the function definition is before the function call.
Function definition:-
Function definition contains programming codes to perform specific task. It consist of
two parts namely function header and function body. Function header is the first line of
function definition. When a function is called, control of the program is transferred to
function header. Function header is followed by body of function insidebraces.

Syntax:
<Return_data_type><Function_name>(<datatype><var1>,<datatype><var2>,...)

{ Statement1....

Statement2....
Statement3....

.....

.....

return (expression);
}

Return statement is used for returning a value and program control from function
definition to calling function. The return statement may or may not return the values.
Function call:-
Function call invokes the function to execute. It makes the control of program jump
from that statement to function definition and executes the codes inside that function.
Syntax:
Function_name(variable1,variable2,......);

When function call occurred, the control flow of the program moves to function
definition, there it checks function header details like function name, no of arguments, data
types of the arguments. If they are matched then moves to function body and executes the
statements in it. Again the control returns to function call after completion of last statement or
first occurrence of return statement in the function body.
Example: Write a C program to add two numbers using user defined functions.

#include<stdio.h>

int add (int, int); // Function prototype/declaration.

void main()

int x=90,y=10,sum; // Calling function.

sum=add(x,y); // x, y are actual arguments, add(x,y) is function call.

printf("\n\n %d + %d = %d\n\n",x,y,sum);

int add(a,b)

{ // a, b are formal arguments, add() is Called function.

int c;

c=a+b;

return c; // returns the value of 'c' from add() tomain().

Output:
90 + 10 = 100
Inter FunctionCommunication:-
Communication between called function and calling function to exchange the
information is called as inter function communication.
The data flow between calling and called functions can be in three ways namely
upward flow, down ward flow and Bi-directional flow. Upward flow and downward flow are
the unidirectional flows where the data flows either from calling function to called function
or called function to calling function. If the data is flowing from calling function to called
function then it is downward flow else if the data is flowing from called function to calling
function then it is upward flow. If the data is flowing from called to calling and also vice
versa then it is bidirectional dataflowing.
While establishing the inter function communication, the arguments can be passed in
two ways namely call by value and call by reference. In call by value, values are passing
through the parameters where as in call by reference the addresses are passed to establish the
communication between called and calling function.
By default in C programming call by value is used to pass the parameters. Here, only
the values of the actual arguments will copy in the formal arguments. Hence, changes made
in formal arguments will not affect the changes in actual arguments in the calledfunction.
In call by reference, the formal arguments copies the address passed from the actual
arguments. Therefore, the changes made in the formal arguments effect the actual arguments.
Here to argument pointer are passed as the values to the function.
Based on the existence of return value and arguments the inter function communication
can be done in four ways namely as follows.
1. With return values and with arguments (Bi directionflow).
2. With return value and without arguments (Upward flow).
3. Without return value and with arguments (Down wardflow).
4. Without return and without arguments (there will be no flow ofdata).
(Or)

Different aspects of function calling:-

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.

o function without arguments and without return value(No arg& no return)


o function without arguments and with return value(No arg& with return)
o function with arguments and without return value(with arg&no return)
o function with arguments and with return value(with arg&with return)
Example for Function without argument and return value

[Link]

1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Rgukt");
11. }

Output

Hello Rgukt

[Link]:-

1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
Example for Function without argument and with return value

[Link] :-

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

program to calculate the area of the square

[Link] :

#include<stdio.h>

1. int sum();
2. void main()
3. {
4. printf("Going to calculate the area of the square\n");
5. float area = square();
6. printf("The area of the square: %f\n",area);
7. }
8. int square()
9. {
10. float side;
11. printf("Enter the length of the side in meters: ");
12. scanf("%f",&side);
13. return side * side;
14. }

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value

[Link]:-

1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24
The sum is 34

program to calculate the average of five numbers.

[Link] :

1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
Example for Function with argument and with return value

[Link] :-

1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Program to check whether a number is even or odd

[Link]:-

1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

C standardLibrary Functions:-

Library functions are the inbuilt function in C that are grouped and placed at a common place called the
library. Such functions are used to perform some specific operations. For example, printf is a library
function used to print on the console. The library functions are created by the designers of compilers. All C
standard library functions are defined inside the different header files saved with the extension .h. We need
to include these header files in our program to make use of the library functions defined in such header files.
For example, To use the library functions such as printf/scanf we need to include stdio.h in our program
which is a header file that contains all the library functions regarding standard input/output.

The list of mostly used header files is given in the following table.

SN Header Description
file

1 stdio.h This is a standard input/output header file. It contains all the library functions regarding
standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.

5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.


9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

Call by value and Call by reference in C:-


There are two methods to pass the data into the function in C language, i.e., call by value and call by
reference.

Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we
can say that the value of the variable is used in the function call in the call by value method.

o In call by value method, we can not modify the value of the actual parameter by the formal parameter.

o In call by value, different memory is allocated for actual and formal parameters since the value of the actual
parameter is copied into the formal parameter.

o The actual parameter is the argument which is used in the function call whereas formal parameter is the argument
which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given below:

1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do
not change by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b
= 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the actual parameter.

o The value of the actual parameters can be modified by changing the formal parameters since the address of the
actual parameters is passed.

o In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the
operations in the function are performed on the value stored at the address of the actual parameters, and the
modified value gets stored at the same address.

Consider the following example for the call by reference:-:-QL CREATE TABLE

1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c


No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the function

2 Changes made inside the function is limited to the Changes made inside the function validate outside of the
function only. The values of the actual parameters do function also. The values of the actual parameters do
not change by changing the formal parameters. change by changing the formal parameters.
3 Actual and formal arguments are created at the different Actual and formal arguments are created at the same
memory location memory location

RecursiveFunctions:
If a function calls itself is called recursive function. A recursive function has two
components namely base case and recursive case. Recursive case is also known as general
case. A base case is the statement that solves the problem and the recursive case is the
statement which calls the function itself recursively to break the problem. Each recursive
function should have the base case, otherwise the function never come out of it. The steps to
design a recursive function are asfollows.
1. Determine the basecase.
2. Determine the recursive case.
3. Combine these base and recursive cases in to afunction.
Example: [Link] a C program to find the factorial of the given number using
recursion.(direct Declaration)
#include<stdio.h>
int factorial(int);
void main()
{
int n=6,fact;
fact=factorial(n);
printf("\n\n %d! = %d\n\n",n,fact);
}
intfactorial(intx){ // recursive function
if(x==0 || x==1)return1; // basecase
else
return(x*factorial(x-1)); // recursivecase
}

Output:
6! = 720

Runtime Initialization: Factorial Recursive


[Link] a C program to find the factorial of the given number using recursion
#include<stdio.h>
int fact(int);
void main()
{
int num,f;
printf("enter a number");
scanf("%d",&num);
f=fact(num);
printf("factorial is =%d\n",f);
}
int fact (int num)
{
if (num==0||num==1)
return 1;
else
return(num*fact(num-1));
}
Disadvantages of recursion:-
1. They don’t significantly reduce the size of the code and improve memoryutilization.
2. Little bit slower than corresponding iterative statements because of repeated function
calloverheads.
3. If the depth recursion is higher, then it may lead to program crash as the stack is
exhausted.
4. Difficult to debug the bugs, especially when global variables areusing.
Advantages of recursion:-
1. The recursive function can used to create clearer and simpler versions of several
algorithms like quicksort.
2. Recursive solutions are often tends to be shorter andsimpler.
3. It follows divide and conquer method.
4. Problems related to artificial intelligence lend themselves to the recursivesolutions.

Differences between recursion and iteration:


The following Table – 4.1 gives the differences between recursion and iteratin.
SNO RECURSION ITERATION
1 It is top downapproach. It is bottom upapproach.
Stack is used while executing
2 No stack is used.
recursion.
3 It uses more memory. It uses relatively less memory.
4 Code can be reduced little bit small. Code size is little bit large.
5 Time complexity is high. Time complexity is relatively low.
Due to repeated functioncall,
6 No overhead in iteration.
recursion has largeoverhead.
Infinite iteration may leads to CPU When memory exhausted then iteration will
7
crashing. stop the execution.
Table – 4.1: Differences between RECURSION and ITERATION

 Strings:-
Group of character is known as string. In C, string can be defined as NULL (\0)
terminated character array which means the last character of the array is NULL. NULL
character at the end signifies that it is end of the array.

Declaring strings:
Syntax: char <string_name> [<size>];

Note: Size of the string always should be “number of characters + 1” as it


requires one more cell for NULL character.
Example: char str[10]; it stores a string with maximum length 9.

String initialization:
Syntax1: char <string_name> [<size>] = “<string>”;

Example: char a[6]= “R”;


Syntax2: char <string_name> [ ] = “<string>”; // It automatically assign the size

as no. Of characters+1

Example: char a[ ]= “RGUKT”;

R G U K T \0
0 1 2 3 4 5
Syntax3: char <string_name> [ ] = {‘c1’, ‘c2’,..........‘cn’, ‘\0’};

Example: char a[ ]={‘R’ ‘G’, ‘U’, ‘K’, ‘T’, ‘\0’} ;


R G U K T \0
0 1 2 3 4 5
In first two syntaxes we use the string constants to initialize the strings where it
doesn’t require mentioning the NULL character specifically. But in syntax3 which
initializes the string as array of characters requires to mentioning the NULL specifically.
While initializing the strings if we are mentioning the size of the string, in such
cases the number of characters should be less than the size of the string, if not then it
would be illegal initialization.
If the size of string is too much larger, then it fills the character from index ‘0’
and the remaining characters automatically initialized as NULL.
Example: char a[10]=”RGUKT”;

R G U K T \0 \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9
Of course, we can access the individual character from the string using its index
number like in array.
In the above example we can access the character as
follows. a[0] retrieves ‘R’
a[1]
retrieves
‘G’ a[2]
retrieves
‘U’ a[3]
retrieves
‘K’ a[4]
retrieves ‘T’
Note: In any compiler a single character always takes ‘1 byte’ of memory. Therefore
the size of array itself indicates number of maximum characters can be stores and
memory required for the string.
String I/O functions :
Thefollowingaretheinputandoutputfunctionsofstringsin c

Input functions: scanf(), gets()


Outputfunctions: printf(),puts()

 The scanf() andprintf() are generic i/o functionsthatthey support all built-in data
types such as int, float, long, double, strings,..etc.

 But gets() and puts() are specialized to scan and print only string data. There is a
little difference between scanf() and gets(), while reading string from keyboard,
the scanf() accepts character by character from keyboard until either anew line (‘\
n’) or blank space is found, which ever comes earlier.

 Whereas“gets()” accepts until a newline is found. That is it accepts white spaces


& tab also, these input functions append a null characterat end of string,
theformatted string %s is used inprintf() and scanf().for example:

Scanning stringwith“scanf()” Scanningstringwith“gets()”


voidmain() voidmain()
{ {
char a[20]; char a[20];
printf(“enterastring) printf(“enterastring:
; ”); gets(a);
scanf(“%s”,a);//scanf(“%s”,&a[0]); printf(“\noutput=%s”,a);
printf(“\n output=%s”, a); }
}
Input:JackandJill//scanftreats as 3 strings Input:JackandJill //gets()treatsassingle
Output: Jack string
Output:JackanJill
The scanf() function consider the jack and Jill as 3 strings, whereas gets() considers as
single string. In case to scan total string using scanf(), then it should be scanf(“%s%s%s”, a,b,c);
here a,b,c are three arrays
The printf()and puts()is work in similar way. AllI/O functions takefirst byte address (base
address of array) as argument and prints the given string using pointer.
Pro gram: The following program is an example of string I/O functions

#include<stdio.h>
#include<string.h
>void main()
{

char name[30];
printf(“Enter name:
“);
gets(name); //Function to read string from
user. printf(“Name: “);
puts(name); //Functiontodisplaystring.
}

Output:
Entername:Rgukt
Name: Rgukt

String Handling Functions In C Language:-


There are many important string functions defined in "string.h" library.

No Function Description
.

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination string.

3) strcat(first_string, concats or joins first string with second string. The result of the string is
second_string) stored in first string.

4) strcmp(first_string, compares the first string with second string. If both strings are same, it
second_string) returns 0.

5) strrev(string) returns reverse string.


6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

1.C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null character '\0'.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={‘R' ,’G’,’U’,’K’,’T’,’O’,’N’,’G’,’O’, ‘L’,’E’, '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }

Output:

Length of string is: 11

2.C Copy String: strcpy()


The strcpy(destination, source) function copies the source string in destination.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={‘R' ,’G’,’U’,’K’,’T’,’O’,’N’,’G’,’O’, ‘L’,’E’, '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }

Output:

Value of second string is:RGUKTONGOLE

3.C String Concatenation: strcat()


The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }

Output:

Value of first string is: helloc

4.C Compare String: strcmp()


The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are
equal.

Here, we are using gets() function which reads string from the console.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal
5.C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function

Example1: In below program, string “Hello” is reversedusing strrev( ) function and output is
displayed as “olleH”

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }

Output:

Enter string: javatpoint


String is: javatpoint
Reverse String is: tnioptavaj

6.C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr()
function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:

Enter string: JAVATpoint


String is: JAVATpoint
Lower String is: javatpoint

7.C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr()
function.

EX:1

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }

Output:

Enter string: javatpoint


String is: javatpoint
Upper String is: JAVATPOINT

EX:2
#include<stdio.h>
#include<string.h
>

intmain()
{

charstr[]=“ModifyThisStringToUpper”;

printf(“%s\n”,strupr(str));

return0;
}

Output:
MODIFYTHISSTRINGTOUPPER

8.C String strstr()


The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is
used to return substring from first match till the last character.

Syntax:

1. char *strstr(const char *string, const char *match)

String strstr() parameters


string: It represents the full string from where substring will be searched.

match: It represents the substring to be searched in the full string.

C++ vs Java

String strstr() example


1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[100]="this is javatpoint with c and java";
5. char *sub;
6. sub=strstr(str,"java");
7. printf("\nSubstring is: %s",sub);
8. return 0;
9. }

Output:

javatpoint with c and java

9)atoi() function : It converts string-value to numeric-value and it converts a numeric-string value to


equivalent integer-value.

Syntax:
intatoi(string);
For example:
printf(“output=%d”,atoi(“123”)+atoi(“234”));

will print 357

10).atol() function: converts along int string value to equivalent long integer
value.

Syntax:long intatol(string);
For example:
printf(“output=%d”,atol(“486384”)-atol(“112233”));

This statement will print 374151

11)Program1: Write a Cprogram to count the number of vowels present in a sentence.

/*programtocount vowels*/
# include<stdio.h>
#include<string.
h>main()
{

charst[80], ch;
intcount=0,i;
printf(“\nEnter thesentence:\n”);
gets(st);
for(i=0;i<strlen(st);i++)
switch(st [i ])
{

case‘A’:
case‘E’:
case ‘I’:
case‘O’:
case‘U’:
case‘a’:
case‘e’:
case‘I’:
case‘o’:
case‘u’:
count++;
break;
}
printf(“\n%dvowelsarepresentinthesentence”,count);

Output:
Enterthesentence:
Thisisabook
5vowelsarepresentinthesentence.

****************** END****************************
Page no :33

You might also like