Unit 3
Unit 3
Chennai
Prepared by:
Dr. P. Robert
Assistant Professor
Department of Computing Technologies
SRMIST-KTR
SRM Institute of Science and Technology,
Chennai
Unit-III
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
1. gets()
2. puts()
3. getchar()
4. putchar()
5. Printf()
String Functions
1. gets()
It is used to take a single input at a time but can be used to input a complete sentence with spaces unlike
scanf(). It stops reading character when the newline character is read or end-of the file is reached.
Declaration
char *gets(char *str)
str- This is the pointer to an array of characters where the C string is stored.
Return Value:
This function returns str on success, and NULL on error or when end of file occurs.
String Functions
Example:
#include <stdio.h>
int main () {
char str[50];
printf("Enter a string : ");
Output:
gets(str);
printf("You entered: %s", str); Enter a string : Robert Jose
You entered: Robert Jose
return(0);
}
String Functions
2. puts()
This function writes strings or lines to stdout, i.e, the output stream. The string is printed with newline and
an integer value is returned.
Declaration
int puts(const char* string)
Example:
# include<stdio.h>
int main(){
// Initializing the string.
char string[] = "SRM University";
// Writing our string to stdout.
puts(string);
return 0; SRM University
}
String Functions
3. getchar()
The getchar() function is the part of the <stdio.h> header file in C. It is used when single character input
is required from the user.
Note:
The function reads the input as an unsigned char; then it casts and return as an int or an EOF.
EOF is returned if the end of the file is reached or an error is occurred.
Declaration
int getchar(void)
The getchar function takes no parameter.
String Functions
Example:
#include<stdio.h> // Including header file
int main(){
int myChar; // creating a variable to store the input
myChar = getchar(); // use getchar to fetch input
printf("You entered: %c", myChar); // print input on screen
return 0; a
You entered: a
}
String Functions
4. putchar()
This function is used for printing character to a screen at current cursor location.
Declaration
putchar(character_variable);
Example:
#include<stdio.h>
void main()
{
int ch;
printf("Press any character\n"); Press any character
ch = getchar(); a
printf("Pressed character is\n");
Pressed character is
putchar(ch);
getch(); /* Holding output */ a
}
String Functions
5. Printf()
It is one of the main output function. This function sends formatted output to the screen.
Declaration
Printf(“format String”, argument list);
The format string can be %d Integer
%c Character
%f Float
%s String
String Functions
5. Printf()
Example:
#include<stdio.h>
int main(){
int num;
printf("Enter a number:");
scanf("%d",&num);
printf("Cube of number is:%d ",num*num*num);
return 0; Enter a number:3
} Cube of number is:27
Built-in String Functions
atoi
strlen
strcat
strcmp
Built-in String Functions
atoi
The atoi() function converts a character string to an integer value. The input string is a sequence of
characters that can be interpreted as a numeric value of the specified return type. The function stops
reading the input string at the first character that it cannot recognize as part of a number.
Syntax:
int atoi(const char *str)
Where
str- String passed to the function
Return value:
If str is a valid input, the function returns the integer number equal to the passed string number. If str has
no valid input, the functions return zero value.
Built-in String Functions
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val1,val2;
char string1[20] = "Jose";
val1 = atoi(string1);
printf("String value = %s\n", string1);
printf("Integer value = %d\n", val1);
char string2[20] = "1984";
val2 = atoi(string2); String value = Jose
printf("String value = %s\n", string2); Integer value = 0
printf("Integer value = %d\n", val2); String value = 1984
return (0);
Integer value = 1984
}
Built-in String Functions
strlen
The strlen() function returns the length of the given string. It doesn't count null character '\0’.
Syntax:
int strlen(const char *str)
Where
Str is the parameter passed to the function.
Return value:
The length of the string is returned in integer type excluding the NULL character.
Built-in String Functions
Example:
#include<stdio.h>
#include<string.h>
int main() {
char name[10] = "Jordin";
printf("The length of the string is %d", strlen(name)); The length of the string is 6
return 0;
}
Built-in String Functions
strcat
The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
Syntax:
char *strcat(char *dest, const char *src)
Where
dest- The pointer to the destination array
src- The pointer to the source array
Return value:
This function returns a pointer to the resulting string dest.
Built-in String Functions
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Welcome to ", str2[] = "India";
strcat(str1, str2);
Welcome to India
puts(str1); India
puts(str2);
return 0;
}
Built-in String Functions
strcmp
Strings can be compared either by using the string function or without using string function. The string
function which is pre-defined in a string.h header file is a strcmp() function. The strcmp() function
consider two strings as a parameter, and this function returns an integer value where the integer value can
be zero, positive or negative.
Syntax:
int strcmp (const char* str1, const char* str2);
Where
Str1- a string
Str2 – a string
Return value
0- If both strings are equal
> 0- It returns a value greater than zero when the matching character of left string has greater ASCII value
than the character of the right strin
< 0 - It returns a value less than zero when the matching character of left string has lesser ASCII value
than the character of the right string
Built-in String Functions
Example:
#include<stdio.h>
#include<string.h>
int main() {
char str1[] = "Hello World!";
char str2[] = "hello World!";
int result = strcmp(str1, str2);
if (result==0)
printf("Strings are equal");
else
printf("Strings are unequal");
printf("\nValue returned by strcmp() is: %d" , result);
return 0; Strings are unequal
} Value returned by strcmp() is: -32
String Functions
sprintf
sscanf
strrev
strcpy
strstr
strtok
sprintf
sprintf stands for "string print". In C programming language, it is a file handling function that is used to
send formatted output to the string. Instead of printing on console, sprintf() function stores the output
on char buffer that is specified in sprintf.
Example:
#include <stdio.h>
int main()
{
char buffer[50];
int a = 15, b = 25, res;
res = a + b;
sprintf(buffer, "The Sum of %d and %d is %d", a, b, res);
printf("%s", buffer);
return 0; The Sum of 15 and 25 is 40
}
sscanf
In C, sscanf() is used to read formatted data. It works much like scanf() but the data will be read from a
string instead of the console.
Return Value
The function returns an int value which represents the total number of items read.
Given there was an error and the string could not be read, an EOF error is returned.
Any other type of error which is encountered while reading is denoted by the function returning -1.
Example:
#include<stdio.h>
int main() {
char* buffer = "Hello";
char store_value[10];
int total_read;
total_read = sscanf(buffer, "%s" , store_value);
printf("Value in buffer: %s",store_value);
printf("\nTotal items read: %d",total_read); Value in buffer: Hello
return 0; Total items read: 1
}
strrev
The strrev(string) function returns reverse of the given string.
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "OMAN"; // initialzing a char array
printf("The string is : %s\n", str); // printing the actual array
strrev(str); // reversing the char array
printf("The string after using function strrev() is : %s\n", str); // printing the reversed array
return 0;
}
strcpy
The strcpy(destination, source) function copies the source string in destination.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]="Oman";
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Predefined Function
int main() {
printf("Hello World!");
return 0;
}
For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:
Function Prototype Declaration
Example:
#include <stdio.h>
/* function statement */
int add(int a, int b); //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.
Function Prototype Declaration
Function Declaration:
A function must be declared globally in a c program to tell the compiler about the function name,
function parameters, and return type.
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.
Function Prototype Declaration
Function Declaration:
A function must be declared globally in a c program to tell the compiler about the function name,
function parameters, and return type.
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.
Actual and Formal Parameters
Example
#include <stdio.h>
void addition (int x, int y) { // Formal parameters
int addition;
addition = x+y;
printf(“%d”,addition);
}
void main () {
addition (2,3); //actual parameters
addition (4,5); //actual parameters
}
Different aspects of function calling
Example
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName(); // function without arguments and without return value
}
void printName()
{ Output:
printf("Students");
}
Different aspects of function calling
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",result);
} Output:
int sum() //Function definition
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Different aspects of function calling
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",result);
} Output:
int sum(int a,int b)
{
return a+b;
}
Different aspects of function calling
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)
{ Output:
printf("Addition of two numbers %d",(a+b));
}
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:
#include <stdio.h>
void swap(int x, int y);
int main () {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a ); Output:
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;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return 0; }
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 passed
argument.
Example:
#include <stdio.h>
int main () {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a ); Output:
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;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return 0; }
Why do we need functions in C programming?