Unit 3 Pps
Unit 3 Pps
UNIT-III
Unit 3 1
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.
Unit 3 2
String Basics
Unit 3 3
String Declaration and Initialization
1. gets()
2. puts()
3. getchar()
4. putchar()
5. Printf()
Unit 3 5
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.
Unit 3 6
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);
}
Unit 3 7
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
}
Unit 3 8
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.
Unit 3 9
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
}
Unit 3 10
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
}
Unit 3 11
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
Unit 3 12
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
Unit 3 13
Built-in String Functions
atoi
strlen
strcat
strcmp
Unit 3 14
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.
Unit 3 15
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
} Unit 3 16
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.
Unit 3 17
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;
}
Unit 3 18
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.
Unit 3 19
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;
}
Unit 3 20
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
Unit 3 21
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
Unit 3 22
String Functions
sprintf
sscanf
strrev
strcpy
strstr
strtok
Unit 3 23
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
}
Unit 3 24
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
}
Unit 3 25
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;
}
Unit 3 26
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;
}
Unit 3 27
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.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char str[100]="types of machine learning algorithms";
char *sub;
sub=strstr(str,"machine");
printf("\nSubstring is: %s",sub);
return 0;
}
Unit 3 28
strtok
The C string manipulation function "strtok()" is used to split a string into tokens or smaller strings
based on a designated delimiter. The "string.h" header file contains the function's declaration.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Delhi,Hyderabad,Noida";
char *token;
token = strtok(str, ",");
while(token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
} Delhi
Hyderabad
Noida
Unit 3 29
In the above example, the comma (,) is used as a delimiter to separate the str string into smaller
tokens. The strtok() function is first invoked with str as its first argument. The function returns a
pointer to the first token, which is kept in the token variable. Once all tokens have been extracted, the
loop resumes by calling strtok() with the delimiter as the second argument and a NULL for the first
argument. The NULL first argument tells strtok() to pick up where the previous call left off.
Unit 3 30
Function Prototype Declaration
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:
Unit 3 31
Function Prototype Declaration
Function Prototype Declaration
return_type function_name(parameter list) {
// function body
}
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.
How to Declare a Function in C
return_type function_name(parameter_list);
Example: int add(int num1, int num2);
Unit 3 32
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.
Unit 3 33
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. Unit 3 34
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. Unit 3 35
Actual and Formal Parameters
Difference between Actual and Formal Parameters
Unit 3 36
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
}
Unit 3 37
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");
}
Unit 3 38
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;
}
Unit 3 39
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;
}
Unit 3 40
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));
}
Unit 3 41
Call by Value & Call by Reference
Unit 3 42
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 */
Unit 3 43
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 );
printf("Before swap, value of b : %d\n", b ); Output:
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;
Unit 3 44
}
Why do we need functions in C programming?
Unit 3 45
Passing array to functions
#include <stdio.h>
int Sum(int num[]);
int main() {
int result, num[] = {23, 55, 22, 3, 40, 18};
result = Sum(num); //Passing array to function
printf(“Sum = %d", result);
return 0;
} Output:
int Sum(int num[]) {
int sum = 0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
Unit 3 46
Passing array elements to functions
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display() Output:
display(ageArray[1], ageArray[2]);
return 0;
}
Unit 3 47
Function Pointers
A block of memory is reserved by the compiler when we declare a variable. To store these memory
addresses, C allows programmers to use the concept of pointers that can hold the address of any other
data type. Pointers can be de-referenced using the asterisk * operator to get the value stored in an
address.
Unit 3 48
Function Pointers
A block of memory is reserved by the compiler when we declare a variable. To store these memory
addresses, C allows programmers to use the concept of pointers that can hold the address of any other
data type. Pointers can be de-referenced using the asterisk * operator to get the value stored in an
address.
Declaring a Function Pointer in C
Unit 3 49
Function Pointers
Example:
#include<stdio.h>
int areaRectangle(int, int);
int main() {
int length, breadth, area;
int (*fp)(int, int);
printf("Enter length and breadth of a rectangle\n");
scanf("%d%d", &length, &breadth);
fp = areaRectangle; Output:
area = (*fp)(length, breadth);
printf("Area of rectangle = %d", area);
return 0;
}
int areaRectangle(int l, int b) {
int area_of_rectangle = l * b;
return area_of_rectangle;
}
Unit 3 50