Unit3 Pps
Unit3 Pps
Unit3 Pps
String Basics - String Declaration and Initialization - String Functions: gets(), puts(),
getchar(),putchar(), printf() - Built-inString Functions: atoi, strlen, strcat, strcmp -
String Functions: sprint, sscanf, strrev, strcpy, strstr, strtok - Operations on Strings -
Function prototype declaration, function definition - Actual and formal parameters -
Function with and without Arguments - Function with and without return values -
Call by Value, Call by Reference - Passing Array to Function - Passing Array
elements to Function - Function Pointers.
STRING BASICS
●
Strings in C are represented by arrays of characters.
Address
Eachof 'P' = 2000
Character is storedofin 'P' = 2001
Address
consecutive memory
Address of 'S' = 2002
location.
9
STRING DECLARATION AND INITIALIZATION
●
String Declaration:
Maximum size - 30
13
#include Outpu
<stdio.h> int t
main() H
{
char greetings[] = "Hello
World!"; printf("%c",
greetings[0]);
return 0;
}
#include Outpu
t
<stdio.h> Jello
int main() { World!
char greetings[] = "Hello
World!"; greetings[0] = 'J';
printf("%s",
greetings); return
0;
} 15
Precautions to be taken while declaring Character Variable :
●
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
− String city;
●
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>
17
2. INITIALIZING STRING [CHARACTER ARRAY] :
●
Whenever we declare a String then it will contain garbage
values inside it. We have to initialize String or Character
array before using it. Process of Assigning some legal
default data to String is Called Initialization of String.
●
There are different ways of initializing String in C
Programming –
❑ Initializing Unsized Array of character
❑ InitializingString Directly
❑ InitializingString Using Character Pointer
19
WAY 1 : UNSIZED ARRAY AND CHARACTER
●
Unsized Array :Array Length is not specified while
initializing character array using this approach
●
Array length is automatically calculated by Compiler
●
Individual characters are written inside single quotes ,
separated by comma to form a list of characters.
complete list is wrapped inside Pair of Curly braces
●
NULL Character should be written in the list because it
is ending or terminating character in the String/Character
Array
●
char name [] = {'P','P','S','\0'};
21
WAY 2 : DIRECTLY INITIALIZE STRING VARIABLE
●
In this method we are directly assigning String to variable
by writing text in double quotes.
●
In this type of initialization , we don’t need to put NULL
or Ending / Terminating character at the end of string. It
is appended automatically by the compiler.
●
char name [ ] = "PPS";
23
WAY 3 : CHARACTER POINTER VARIABLE
●
Declare Character variable of pointer type so that it
can hold the base address of “String”
●
Base address means address of first array element
i.e (address of name[0] )
●
NULL Character is appended
Automatically char *name = "PPS";
25
STRING FUNCTIONS
− puts( ) − strcmp( )
− gets( ) − sprintf( )
− getchar( ) − sscanf( )
− − strrev( )
putchar( )
− printf( ) − strcpy( )
− atoi( ) − strstr()
− strlen( ) − strtok()
− strcat ( )
27
GETS():
SYNTAX FOR ACCEPTING STRING :
char * gets ( char * str ); OR
gets( <variable-name> )
Example :
#include<stdio.h>
void main()
{
char name[20]; printf("\
nEnter the Name : ");
gets(name);
}
29
❑ Whenever gets() statement encounters then characters entered by user
(the string with spaces) will be copied into the variable.
❑ If user start accepting characters , and if new line character appears
then the newline character will not be copied into the
string variable(i.e name).
❑ A terminating null character is automatically appended after the
characters copied to string variable (i.e name)
❑ gets() uses stdin (Standard Input Output) as source, but it does not
include the ending newline character in the resulting string and does
not allow to specify a maximum size for string variable (which can
lead to buffer overflows).
31
Some Rules and Facts :
A. %s is not Required :
●
Value Accepted : Problem solving\n
●
Value Stored : Problem (\n Neglected)
solving
33
B. Spaces are allowed in gets() :
gets(name);
Whenever the above line encounters then interrupt will wait
for user to enter some text on the screen. When user starts
typing the characters then all characters will be copied to
string and when user enters newline character then process of
accepting string will be stopped.
35
2. PUTS():
Way 1 :Messaging
●
puts(" Type your Message / Instruction ");
●
Like Printf Statement puts() can be used to display message.
Way 2 : Display String
●
puts(string_Variable_name) ;
Notes or Facts :
●
puts is included in header file “stdio.h”
●
As name suggest it used for Printing or Displaying Messages
or Instructions.
37
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char string[] =
"This is an
example string\
n";
puts(string); //
String is variable
Here
puts("String"; //
String is in
Double Quotes
getch(); 39
}
GETCHAR():
●
Getchar() function is also one of the function which is
used to accept the single character from the user.
●
The characters accepted by getchar() are buffered until
RETURN is hit means getchar() does not see the
characters until the user presses return. (i.e Enter Key)
41
●
When control is on above line then getchar() function will accept
the single character.
●
After accepting character control remains on the same line.
●
When user presses the enter key then getchar() function will read
the character and that character is assigned to the variable ‘ch’.
Parameter Explanation
43
EXAMPLE 1 :
IN THE FOLLOWING EXAMPLE WE ARE JUST ACCEPTING THE
SINGLE CHARACTER AND PRINTING IT ON THE CONSOLE –
main()
Output :
{ rukcdnhjmjcghkcg
char ch; Accepted Character : r
ch = getchar();
printf("Accepted Character : %c",ch);
}
45
EXAMPLE 2 : ACCEPTING STRING (USE ONE OF THE
LOOP)
#include<stdio.h>
void main()
{
int i = 0;
char name[20]; printf("\
nEnter the Name : ");
while((name[i]=getchar())!='\n’)
i++ ;/*while loop will accept
the
one character at a time and
check it with newline character.
Whenever user enters newline
character then control comes
out of the loop.*/
} 47
PUTCHAR():
●
Individual Character is Given as
parameter to this function.
●
We have to explicitly mention
Character.
49
Way 2 : Taking Variable as Parameter
putchar(a);
// Display Character Stored in ‘a’
❑
Input Parameter is Variable of Type “Character”.
❑
This type of putchar() displays character stored in variable.
51
Example: Output:
#include<stdio.h> C programming
int main()
{
char string[] = "C programming\n";
int i=0;
while(string[i]!='\0')
{
putchar(string[i]);
i++;
}
return 0;
}
53
PRINTF():
Syntax :
Notes or Facts :
printf is included in header file “stdio.h”
As name suggest it used for Printing or Displaying Messages or
Instructions Uses :
●
Printing Message
●
Ask user for entering the data ( Labels . Instructions )
●
Printing Results
55
ATOI FUNCTION:
●
Atoi = A to I = Alphabet to Integer
●
Convert String of number into Integer
●
Syntax:num = atoi(String);
57
SIGNIFICANCE :
●
Can Convert any String of Number into Integer Value that can Perform
the arithmetic Operations like integer
●
Header File : stdlib.h
59
OTHER INBUILT TYPECAST FUNCTIONS IN C PROGRAMMING
LANGUAGE:
❑
Typecasting functions in C language performs data type
conversion from one type to another.
❑
Some other functions are given below
●
atof() Converts string to float
●
atoi() Converts string to int
●
atol() Converts string to long
●
itoa() Converts int to string
●
ltoa() Converts long to string
61
STRLEN FUNCTION: Finding length of string
Point Explanation
No of Parameters - 1
Parameter Taken - Character Array Or String
Return Type - Integer
Description - Compute the Length of the String
Header file - string.h
63
Different Ways of Using strlen() :
●
There are different ways of using strlen function. We can pass
different parameters to strlen() function.
65
67
Way 2 : Taking String Variable which is Already Initialized using Pointer
char *str = "priteshtaral";
int length ;
length = strlen(str);
printf("\nLength of String : %d ", length);
69
STRCAT FUNCTION:
Function takes 2 Strings / Character Array as Parameter
●
Appends second string at the end of First String.
Parameter Taken - 2 Character Arrays / Strings
Return Type - Character Array /
String
●
Syntax :
71
Ways of Using Strcat Function :
Way 1 : Taking String Variable as Parameter
char str1[20] = “Don” ;str2[20] = “Bosqo”;
strcat(str1,str2);
puts(str1);
73
STRCMP FUNCTION:
●
Function takes two Strings as parameter.
●
It returns integer .
75
1.It starts with comparing the ASCII values of the first
characters of both strings.
2.If the first characters in both strings are equal, then this
function will check the second character, if they are also equal,
then it will check the third, and so on till the first unmatched
character is found or the NULL character is found.
If a NULL character is found, the function returns zero as
both strings will be the same.
77
Output
79
4. If a non- matching character is found,
•If the ASCII value of the character of the first string is
greater than
that of the second string, then the positive difference ( > 0)
between their ASCII values is returned.
81
Output
Strings are
unequal Value of
result: 19
83
•If the ASCII value of the character of the first string is less
than that of the second string, then the negative difference (
< 0) between their ASCII values is returned.
85
Output
Strings are unequal
Value returned by strcmp()
is: -5
87
SPRINTF FUNCTION: sends formatted output to String
●
Output is written into string instead of displaying it on the
output devices.
●
Return value is integer ( i.e Number of characters actually placed
in array / length of string ).
●
String is terminated by ‘\0’.
Syntax :
int sprintf(char
*buf,char
format,arg_list
);
89
Example : Output:
My age is 23
int age = 23 ;
char str[100];
sprintf( str , "My age is %d",age);
puts(str);
Analysis of Source Code: Just keep in mind that
❑
Assume that we are using printf then we get output “My age is 23”
❑
What printf will do ? —– Just Print the Result on the Screen
❑
Similarly Sprintf stores result “My age is 23” into string str instead of
printing it.
91
int main() {
float num = 9.34;
printf("I'm a float, look: %f\n", num);
char output[50]; //for storing the converted
string
sprintf(output, "%f", num);
printf("Look, I'm now a string: %s", output);
}
Output
I'm a float, look: 9.340000
Look, I'm now a string: 9.340000
93
int main() {
char output[50];
int num1 = 3, num2 = 5,
ans; ans = num1 * num2;
sprintf(output,"%d multiplied by %d is
%d",num1,num2,ans); printf("%s", output);
return 0;
}
Output
3 multiplied by 5 is 15
95
SSCANF FUNCTION:
Syntax :
int sscanf(const char *str, const char *format, ...);
1.Parsing Strings
2.Reading Formatted Data
3.Converting String to Number
4.Reading Data from Buffer
97
#include
<stdio.h> int
main() {
char date[11] = "12-10-
2023"; int day, month,
year;
sscanf(date, "%d-%d-
%d", &day, &month,
&year);
printf("Day: %d, Month: %d, Year: %d\n",
day, month, year);
return 0;
}
99
Example
#include <stdio.h>
int main ()
{
char buffer[30]="Fresh2refresh 5 ";
char name [20];
int age;
sscanf (buffer,"%s
%d",name,&age);
printf ("Name : %s \n Age : %d \n",name,age);
return 0;
}
101
Syntax :
STRSTR FUNCTION:
char *strstr(const char *s1, const char *s2);
●
Finds first occurrence of sub-string in other string
Features :
●
Finds the first occurrence of a sub string in another string
Main Purpose : Finding Substring
Header File : String.h
●
Checks whether s2 is present in s1 or not
●
On success, strstr returns a pointer to the element in s1 where
107
Example 3 Output :
Passing Direct Strings The substring is:
google.com
#include<stdio.h>
#include<string.h> void main()
{
char *ptr; ptr=strstr(“www.google.com
",“google"); printf("The substring is:
%s", ptr);
}
109
STRREV(): reverses a given string in C language.
Syntax
char *strrev(char *string);
●
strrev() function is nonstandard function which may not available in
standard library in C.
113
STRCPY FUNCTION: Syntax :
char * strcpy ( char *string1, char *string2 ) ;
115
●
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 entire
string,
source string value won’t be copied into destination string.
●
For example, consider destination string length is 20 and source
119
Example 2 Output
#include <stdio.h> source string = hihello
#include <string.h> target string =
target string after
int main( ) strcpy( ) = hihello
{
char source[ ] = "hihello" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf("target string after strcpy()=%s",target) ;
return 0; }
121
STRTOK FUNCTION
●
tokenizes/parses the given string using delimiter.
Syntax
char * strtok ( char * str, const char * delimiters );
For example, we have a comma separated list of items from a file
and we want individual items in an array.
●
Splits str[] according to given delimiters and returns next token.
●
It needs to be called in a loop to get all tokens.
●
It returns NULL when there are no more tokens.
123
EXAMPLE
#include <stdio.h>
#include <string.h>
int main()
{
char str[] =
"Problem_Solving_
in_c";//Returns
first token
char* token = token);
printf("%s\n",
Output:
strtok(str,
token "_");
= strtok(NULL, "_");
}//Keep printing tokens Problem
return
while one0;of the
}delimiters present in Solving
str[].
while (token != in
NULL)
{ C
125
ARITHMETIC CHARACTERS ON STRING
●
C Programming Allows you to Manipulate on String
●
Whenever the Character is variable is used in the expression
then it is automatically Converted into Integer Value called
ASCII value.
●
All Characters can be Manipulated with that Integer
Value.(Addition,Subtraction)
Examples :
ASCII value of : ‘a’ is 97
ASCII value of : ‘z’ is 121
127
POSSIBLE WAYS OF MANIPULATION :
Way 1:Displays ASCII value[ Note that %d in Printf]
char x = 'a';
printf("%d",x); // Display Result = 97
Way 2 :Displays Character value[Note that %c in
Printf]
char x = 'a';
129
Way 4 Displays Next Character value[Note that %c in Printf ]
char x = 'a' + 1;
printf("%c",x); // Display Result = 'b‘
131
FUNCTION DECLARATION AND DEFINITION:
133
Defining a function
The general form of a function definition in C programming
language is as follows −
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a
function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
135
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.
137
main()
{
display();
}
void mumbai() We have written functions in the above
{ specified sequence , however functions
printf("In mumbai"); are called in which order we call them.
}
void pune()
Here functions are called this sequence –
{
india();
main() ->display() -
}
>
void display()
pune() -> india() ->
{
mumbai().
pune();
}
void india()
{
mumbai();
}
139
Why Funtion is used???
141
3. Individual functions can be easily built,tested
❑ As we have developed C application in modules we can test each and
every module.
❑ Unit testing is possible.
❑ Writing code in function will enhance application development
process.
4. Program development become easy
5. Frequently used functions can be put together in the customized library
❑ We can put frequently used functions in our custom header file.
❑After creating header file we can re use header file. We can include header file
in other program.
6. A function can call other functions & also itself
❑ Function can call other function.
❑ Function can call itself , which is called as “recursive” function.
❑ Recursive functions are also useful in order to write system functions.
7. It is easier to understand the Program topic
❑ We can get overall idea of the project just by reviewing function names.
143
How Function works in C Programming?
145
Explanation : How function works in C Programming ?
147
Note : Calling a function halts execution of the current function ,
it will execute called function
149
Function Prototype Declaration
151
Function Prototype Declaration
return_type function_name(parameter list)
{ How to Declare a Function in C
// function body return_type function_name(parameter_list);
The return_type specifies the type of value that the function will
return. If the function does not return anything, the return_type will be
void.
The function_name is the name of the function, and the
parameter list specifies the parameters that the function will take in.
153
Function Prototype Declaration: Example:
#include <stdio.h>
//Function declaration
/* function definition */
int add(int a, int b)
{
return a + b;
}
int main() { // Starting point of execution
int result = add(2,3); // Calling Function
printf("The result is %d\n", result);
return 0;
}
Function definition:
It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be returned from the
function.
155
FUNCTION PROTOTYPE DECLARATION
FUNCTION DECLARATION:
A FUNCTION MUST BE DECLARED GLOBALLY IN A C PROGRAM TO TELL THE COMPILER ABOUT THE
Function Call:
Function can be called from anywhere in the program. The parameter
list must not differ in function calling and function declaration. We must pass
the same number of functions as it is declared in the function declaration.
Actual Parameters
Actual parameters are values that are passed to a function when it is invoked.
Formal Parameters
Formal parameters are the variables defined by the function that receives
values when the function is called.
157
FUNCTION PROTOTYPE DECLARATION IN C PROGRAMMING
FUNCTION PROTOTYPE DECLARATION IS NECESSARY IN ORDER TO PROVIDE
• prototype declaration
• function prototype
159
Points to remember
161
Actual and Formal Parameters
163
Actual and Formal Parameters
Example
#include <stdio.h>
void addition (int x, int y) { // Formal parameters
int addition;
addition = x+y;
printf(“%d”,ad
dition);
}
void main () {
addition
(2,3); //actual
parameters
addition 165
(4,5); //actual
Different aspects of function calling: Type 1
Output:
Example
#include<stdio.h>
void
printName();
void main ()
{
printName(); // function without arguments and without return value
printf("Hello
} ");
void printName()
{
printf("Students");
}
167
Different aspects of function calling: Type 2
Output:
Example
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing
to calculate the
sum of two
numbers:");
result = sum();
//Function
without
arguments
and with
return value
printf("%d",res
ult);
169
}
Different aspects of function calling : Type 3 Output:
Example
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\n sum
of two
numbers:");
result =
sum(2,3);
//Function
with
arguments
and with
return value
printf("%d",res
ult); 171
}
Different aspects of function calling: Type 4 Output:
Example
#include<stdio.h>
void sum();
void main()
{
int result;
sum(2,3);
//Function
with
arguments
and no return
value
}
void sum(int a,int
b)
{
printf("Additio
n of two
numbers %d", 173
Call by Value & Call by Reference
CALL BY VALUE
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
Example: Output:
#include <stdio.h>
void swap(int x, int y);
int main () {
int a = 100;
int b =
200;
printf("Bef
ore swap,
value of a :
%d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int x, int y) {
int temp;
CALL BY REFERENCE
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the parameter affect the
Output:
•passed argument.
•Example:
•#include <stdio.h> int main ()
{
• int a = 100;
• int b = 200;
• printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
• swap(&a, &b);
• printf("After swap, value of a : %d\n", a );
• printf("After swap, value of b : %d\n", b ); return
0;
•}
• void swap(int *x, int *y) { int temp;
Why do we need functions in C programming?