Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit-4_Strings and Functions

The document provides an overview of string operations and functions in C programming, detailing string declaration, initialization, and manipulation techniques such as concatenation, comparison, and length calculation. It also introduces user-defined functions, explaining their properties, declaration, and types, along with examples of function usage. The content is structured for educational purposes at RV College of Engineering, focusing on practical programming skills.

Uploaded by

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

Unit-4_Strings and Functions

The document provides an overview of string operations and functions in C programming, detailing string declaration, initialization, and manipulation techniques such as concatenation, comparison, and length calculation. It also introduces user-defined functions, explaining their properties, declaration, and types, along with examples of function usage. The content is structured for educational purposes at RV College of Engineering, focusing on practical programming skills.

Uploaded by

Aarsh Bajaj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 102

Go, change the

RV College world
of
Engineering

Unit -4
Strings

1
RV College
of Go, change the world
Engineerin
g

Contents

1. Strings Introduction, Operations on strings- finding length of a


string, converting characters of a string into uppercase and
lowercase, Concatenating two strings, appending a string to another
string, comparing two string, reversing a string. String and character
Built in functions.
2. Functions Introduction, Using functions, Function
declaration/function prototype, Function definition, Function call,
Return statement

2
RV College
of
Engineerin
g
Strings Go, change the world

• A string is nothing but the collection of the individual array elements


or characters. // Character Array
• String is enclosed within Double quotes.
• “programming" is a example of String. char arr[] =“programming”;
• Each Character Occupy 1 byte of Memory.
• Size of “programming“ = 11 bytes char arr[]=“Hello”; H E L L O
String is always Terminated with NULL Character (‘\0′).
• char word[20] = “‘p’ , ‘r’ , ‘o’ , ‘g’ , ‘r’ , ‘a’ , ‘m’ , ‘m’ , ‘I’ , ‘n’ , ‘g’ , ‘\
0’” 3
RV College
Go, change the world
of
Engineerin
g
NULL Character

• NULL Character is also known as string terminating character.


• It is represented by “\0”.
• NULL Character is having ASCII value 0
• NULL terminates a string, but isn’t part of it
• important for strlen() – length doesn’t include the NULL strlen()

4
RV College
Go, change the world
of
Engineerin
g
Declaration of a string
• Since we cannot declare string using String Data Type, instead of which
we use array of type “char” to create String.

Syntax :

• char String_Variable_name [ SIZE ] ;

Examples :

• char city[30];

• char name[20];

• char message[50]; 5
RV College
Go, change the world
of
Engineerin
g
Declaration of a string cont…

6
7
Rules for declaring a string
RV College
of Go, change the world
Engineerin
g

•String / Character Array Variable name should be legal C Identifier.


•String Variable must have Size specified.
•char city[];
•Above Statement will cause compile time error.
•Do not use String as data type because String data type is included in later
languages such as C++ / Java. C does not support String data type
•When you are using string for other purpose than accepting and printing data
then you must include following header file in your code– #include<string.h>
8
RV College
Go, change the world
of
Engineerin
g
Initializing String (Character Array)
• Process of Assigning some legal default data to String is Called Initialization
of String.
•A string can be initialized in different ways. We will explain this with the help
of an example.
• Below is an example to declare a string with name as str and initialize it with
“HelloWorld”.
1. char str[] = “HelloWorld";
2.char str[50] = “HelloWorld";
3.char str[] = {‘H','e',’l',’l',’o',’W','o','r',’l',’d','\0'};
9
RV College
Go, change the world
of
Engineerin
g
String Example
#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

10
Reading Strings
RV College
of Go, change the world
Engineerin
g

11
Writing Strings
RV College
of Go, change the world
Engineerin
g

12
Suppressing Input
RV College
of Go, change the world
Engineerin
g

13
Length
RV College
of Go, change the world
Engineerin
g

14
RV College
of
Engineerin
Converting Character of Strings to Upper Case
Go, change the world
g

15
RV College
Go, change the world
of
Engineerin
g
Appending

16
Comparing Two Strings
RV College
of Go, change the world
Engineerin
g

17
RV College
Go, change the world
of
Engineerin
g
Reversing a String

18
Extracting a substring from Right of the String
RV College
of Go, change the world
Engineerin
g

19
Extracting a substring from Middle of the String
RV College
of Go, change the world
Engineerin
g

20
Insertion
RV College
of Go, change the world
Engineerin
g

21
Indexing
RV College
of Go, change the world
Engineerin
g

22
Deletion
RV College
of Go, change the world
Engineerin
g

23
Replacement
RV College
of Go, change the world
Engineerin
g

24
Array of Strings
RV College
of Go, change the world
Engineerin
g

25
RV College
of Go, change the world
Engineerin
g

Write a program to read and print the names of n students in the class

26
Pointers and Strings
RV College
of Go, change the world
Engineerin
g

• int puts(const char *s); Here the constant modifier is used to assure the
user that the function will not modify the contents pointed to by the source
pointer. Note that the address of the pointer is passed to the function as
27
the argument.
RV College
of
Engineerin
Functions of string.h Go, change the world
g

Function Purpose Example Output

Strcpy(); Makes a copy of a string strcpy(s1, “Hi”); Copies “Hi” to ‘s1’


variable
Strcat(); Appends a string to the strcat(“Work”, “Hard”); Prints “WorkHard”
end of another string

Strcmp(); Compare two strings strcmp(“hi”, “bye”); Returns -1.


alphabetically
Strlen(); Returns the number of strlen(“Hi”); Returns 2.
characters in a string

Strrev(); reverses a given string Strrev(“Hello”); olleH


Strlwr(); Converts string to Strlwr(“HELLO”); hello
lowercase
Strupr(); Converts string to Strupr(“hello”); HELLO
uppercase
28
RV College
of
Engineerin
String Copy (strcpy) Go, change the world
g

• strcpy( ) function copies contents of one string into another string.

• Syntax : strcpy (destination_string , source_string );

• Example:-strcpy ( str1, str2) – It copies contents of str2 into str1.

• strcpy ( str2, str1) – It copies contents of str1 into str2.


• If destination string length is less than source string, entire source string value won’t be
copied into destination string. For example, consider destination string length is 20 and
source string length is 30. Then, only 20 characters from source string will be
copied into destination string and remaining 10 characters won’t be copied and will
be truncated.
29
String Concat (strcat)
RV College
of Go, change the world
Engineerin
g

• strncat( ) function in C language concatenates (appends) portion of one string at the end
of another string.

• Syntax : strncat ( destination_string , source_string, size);

• Example:-strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of


str2.

• As you know, each string in C is ended up with null character (‘\0’).

• In strncat( ) operation, null character of destination string is overwritten by source string’s


first character and null character is added at the end of new destination string which is
created after strncat( ) operation.
30
String Compare (strcmp)
RV College
of Go, change the world
Engineerin
g

strcmp( ) function in C compares two given strings and returns zero if they are same.

If length of string1 < string2, it returns < 0 value that is -1.

If length of string1 > string2, it returns > 0 value that is 1

If length of string1 = string2 it returns 0.

• Syntax : strcmp (str1 , str2 );strcmp( ) function is case sensitive. i.e, “A” and “a” are
treated as different characters.

31
String Concat (strcat)
RV College
of Go, change the world
Engineerin
g

• strncat( ) function in C language concatenates (appends) portion of one string at the end
of another string.

• Syntax : strncat ( destination_string , source_string, size);

• Example:-strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of


str2.

• As you know, each string in C is ended up with null character (‘\0’).

• In strncat( ) operation, null character of destination string is overwritten by source string’s


first character and null character is added at the end of new destination string which is
created after strncat( ) operation.
32
String Length (strlen)
RV College
of Go, change the world
Engineerin
g

•strlen( ) function in C gives the length of the given


string.
•Syntax : strlen(str);

•strlen( ) function counts the number of characters in a given


string and returns the integer value.
•It stops counting the character when null character is found. Because,
null character indicates the end of the string in C.

33
34
35
36
37
Exercise Programs
1Write a program to calculate the length of string without builtin functions
• #include <stdio.h>
• int main() {
• char s[] = "Programming is fun";
• int i;

• for (i = 0; s[i] != '\0'; ++i);



• printf("Length of the string: %d", i);
• return 0;
• }
38
String concatenation without
strcat()

39
Copying a string without strcpy()

40
Find the frequency of a character in
a string

41
42
RV College
of Go, change the world
Engineerin
g

END of Strings in UNIT-4

43
Go, change the world
RV College
of
Engineering

INTRODUCTION TO C PROGRAMMING (22ES14A)

UNIT IV
Functions
(User Defined Functions)
RV College of Go, change the world
Engineering

FUNCTIONS

 C enables programmers to break up the program into segments known as functions each of
which can be written more or less independently of each other.
 A function in C language is a block of code that performs a specific task.
 Every function in C program performs a well defined task.

 It has a name and it is reusable i.e. it can be executed from as many different parts in a C
Program as required.

 It also optionally returns a value to the calling program.


RV College of Go, change the world
Engineering

Properties of C Functions:
 Every function has a unique name. This name is used to call function from “main()” function.
A function can be called from within another function.
 A function is independent and it can perform its task without intervention from or interfering
with other parts of the program.
 A function performs a specific task. A task is a distinct job that your program must perform as
a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.
RV College of Go, change the world
Engineering

Properties of C Functions:

 A function returns a value to the calling program.

 This is optional and depends upon the task your function is going to accomplish.

 Suppose you want to just show few lines through function then it is not necessary to return a value.

 But if you are calculating area of rectangle and wanted to use result somewhere in program then you
have to send back (return) value to the calling function.
Main calls the function named func1(), so it’s called the calling
function
func1() is the called function.

48
Function calling another function.

Note: When the compiler encounters a function call, instead of


executing the next statement in the calling function, the control
jumps to the statements of the called function.
After the called function is executed, control is shifted back to the
calling program.
A function can be called multiple times
in a program.

49
A function consist of two parts:
•Declaration: the function's name, return type, and parameters (if
any)
•Definition: the body of the function (code to be executed)

For code optimization, it is recommended to separate the


declaration and the definition of the function.
You will often see C programs that have function declaration
above main(), and function definition below main().
This will make the code better organized and easier to read:

50
Function name and number of parameters, type of arguments must be same as in the function
declaration/header.

51
•The name of the variable in the function header (declaration or definition) does not need to match the
name of the variable in the function call.
•The names of arguments in a function call are independent of the names in the function header.
•The function header (declaration or definition) specifies the parameter names for internal use.
•The linkage between the two is made through the values passed, not through the names.

#include <stdio.h>

// Function declaration (prototype)


int addNumbers(int a, int b);

// Function definition
int addNumbers(int x, int y) {
return x + y;
}

int main() {
int num1 = 5, num2 = 10;

// Function call
int result = addNumbers(num1, num2); // num1 and num2 used here
printf("Sum: %d\n", result);

return 0;
}

52
RV College of Go, change the world
Engineering

Types of functions in C

1. void function(void)

2. void function(int)

3. int function(void)

4. int function(int)
RV College of Go, change the world
Engineering

Type-1

void function(void)
RV College of Go, change the world
Engineering

Type-1: void function(void)


RV College of Go, change the world
Engineering

Type-1: void function(void)

#include<conio.h>
#include<stdio.h>
void rvce(void); //function declaration
void main()
{
clrscr();
rvce(); //function call
getch();
}
void rvce(void) //function definition
{
printf(”rvce");
}
RV College of Go, change the world
Engineering

Output:
Rvce

We can call a function for more than once in main.


RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>
void rvce(void);

void main()
{
clrscr();

rvce();
rvce();
getch();
}
void rvce(void)
{
printf(”rvce");
}
RV College of Go, change the world
Engineering

Type-1: void function(void)

#include<conio.h>
#include<stdio.h>
void rvce(void); //function declaration
void main()
{
clrscr();
rvce(); //function call
getch();
}
void rvce(void) //function definition
{
printf(”rvce");
}
RV College of Go, change the world
Engineering

Output:
rvce rvce

We can build/call more than one functions in our program.


61
RV College of Go, change the world
Engineering

#include<stdio.h>

void rvce(void);
void college(void);

void main()
{
clrscr();
rvce();
college();
}

void rvce(void)
{
printf(”rvce");
}

void college (void)


{
printf(“college is rvce");
}
RV College of Go, change the world
Engineering

Output
rvce
college is rvce
RV College of Go, change the world
Engineering

Type-2

void function(int)
RV College of Go, change the world
Engineering
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

void square(int);

void main()
{
clrscr();

square(5);

getch();
}

void square(int x)
{
printf("Square is %d",x*x);
}
RV College of Go, change the world
Engineering
Output
Square is 25

68
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

void table(int);

void main()
{
clrscr();

table(5);

getch();
}

void table(int x)
{
for(int a=1;a<=10;a++)
printf("%d*%d=%d\n",a,x,a*x);
}
RV College of Go, change the world
Engineering
RV College of Go, change the world
Engineering

Output

1*5=5
2*5=10
3*5=15
4*5=20 We can pass more than one arguments to a function, each
5*5=25
6*5=30 can have different type/same type.
7*5=35
8*5=40
9*5=45
10*5=50
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

void add(int, int);

void main()
{
clrscr();

add(5, 7);

getch();
}

void add(int x, int y)


{
printf(“Addition is %d",x+y);
}
RV College of Go, change the world
Engineering

Output

Addition is 12
RV College of Go, change the world
Engineering

Write a program to generate a loop between two numbers.(Use functions to


achieve the task)
#include<conio.h>
#include<stdio.h>

Void makeloop(int, int);

void main()
{
clrscr();

makeloop (2, 15);

getch();
}

void makeloop (int x, int y)


{
for(int a=x; a<=y; a++)
printf(“%d,”, a);
}
RV College of Go, change the world
Engineering

Output

2,3,4,5,6,7,8,9,10,11,12,13,14,15
RV College of Go, change the world
Engineering

Edit same program, get two numbers input from user, then
make a loop between these numbers.

Ex:
Please input two numbers: 5 20

5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

Void makeloop(int, int);

void main()
{
clrscr();
int start, end

printf(“Plzz input two numbers:”);


scanf(“%d%d”, start, end);

makeloop (start, end);

getch();
}

void makeloop (int x, int y)


{
for(int a=x; a<=y; a++)
printf(“%d,”, a);
}
RV College of Go, change the world
Engineering

Type-3

int function(void)
RV College of Go, change the world
Engineering
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

int sum(void);

void main()
{
clrscr();
int a;

a=sum();
printf(“Sum is %d”, a);
getch();
}
int sum(void)
{
int x=2, y=3, z;
z=x+y;

return(z);
}
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

int sum(void);

void main()
{
clrscr();
int a;

a=sum();
printf(“Sum is %d”, a);
getch();

int sum(void)
{
int x=2, y=3, z;
z=x+y;

return(z);
}
RV College of Go, change the world
Engineering

Return Keyword
 In functions, where we return any value, we usually use a keyword
“return”, and the value, which is to be returned is written inside braces,
shown after return.
 Example: return(z);
 The above statement will pass the value of z to the left side variable of
calling function.
 ie: a=sum();
 Hence the value in z, which is 5 in our program is passed to a.
RV College of Go, change the world
Engineering

Type-4
Returns a value.

int function(int)

Passes the argument(s).


RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>

int sum(int, int);

void main()
{
clrscr();
int a;

a=sum(2,3);
printf(“Sum is %d”, a);
getch();

int sum(int x, int y)


{

z=x+y;

return(z);
}
RV College of Go, change the world
Engineering

#include<conio.h>
#include<stdio.h>
int sum(int, int);

void main()
{
clrscr();
int a;

a=sum(2,3);
printf(“Sum is %d”, a);
getch();

int sum(int x, int y)


{

z=x+y;
return(z);
}
86
87
88
When a function is called, a calling function may have to pass some value to the called function.
There are two ways in which arguments can be passed to the called function.
a)Pass by value :The value of the variables are passed by the calling function to the called function
b)Pass by reference:The address of the variable are passed by the calling function the called function

Pass by value:In call by value method, the called function creates new variables to store the arguments
passed to it.Therefore, the called function uses the copy of arguments to perform the intended task.

•There are two copies of parameters stored in different memory locations.

•One is the original copy and the other is the function copy.

•Any changes made inside functions are not reflected in the actual parameters of the
caller.

89
90
91
The called function could not modify the value of the argument that was passed to
it.Incase, the value has not been changed , the programmer will have to modify the
program and add return statement to it.

92
93
Pass by Reference:In call by reference method of parameter passing, the address of the
actual parameters is passed to the function as the formal parameters. In C, we use
pointers to achieve call-by-reference.
•Both the actual and formal parameters refer to the same locations.

•Any changes made inside the function are actually reflected in the actual parameters
of the caller.

•In call-by-reference, the function receives implicit reference to the argument , rather
than the copy of its value.Therefore, the function can modify the values of the
variable and that change gets reflected in the calling function as well.

94
95
96
97
Recursion is the technique of making a function call itself. This technique provides
a way to break complicated problems down into simple problems which are easier
to solve.
Recursion is the process of a function calling itself repeatedly till the given
condition is satisfied. A function that calls itself directly or indirectly is called a
recursive function and such kind of function calls are called recursive calls.

In C, recursion is used to solve complex problems by breaking them down into


simpler sub-problems. We can solve large numbers of problems using recursion in
C. For example, factorial of a number, generating Fibonacci series, generating
subsets, etc.

98
Eg:

Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers together
by breaking it down into the simple task of adding two numbers:

99
The fundamental of recursion consists of two objects
which are essential for any recursive function. These
are:
1.Recursion Case

2.Base Condition

1. Recursion Case

The recursion case refers to the recursive call present


in the recursive function. It decides what type of
recursion will occur and how the problem will be
divided into smaller subproblems.

2. Base Condition

The base condition specifies when the recursion is


going to terminate. It is the condition that determines
the exit point of the recursion.
100
#include <stdio.h> int main() {
int n, i;
// Function to calculate the nth Fibonacci
number printf("Enter the number of terms: ");
int fibonacci(int n) { scanf("%d", &n);
if (n == 0) {
return 0; // Base case: 0th Fibonacci printf("Fibonacci Series: ");
number is 0 for (i = 0; i < n; i++) {
} else if (n == 1) { printf("%d ", fibonacci(i)); // Call the recursive function
return 1; // Base case: 1st Fibonacci }
number is 1 printf("\n");
} else {
return fibonacci(n - 1) + fibonacci(n - 2); return 0;
// Recursive case }
}
}

101
RV College of Go, change the world
Engineering

End of the Functions in Unit - 4

You might also like