0% found this document useful (0 votes)
1 views86 pages

Unit 3arraystringfunctions 201219064627

The document outlines the curriculum for a programming course at SRM Institute of Science & Technology, focusing on arrays, strings, and functions. It covers topics such as initializing and accessing 2D arrays, string functions, and function declarations with various argument types. Additionally, it addresses common programming errors related to arrays and provides examples of code implementations.

Uploaded by

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

Unit 3arraystringfunctions 201219064627

The document outlines the curriculum for a programming course at SRM Institute of Science & Technology, focusing on arrays, strings, and functions. It covers topics such as initializing and accessing 2D arrays, string functions, and function declarations with various argument types. Additionally, it addresses common programming errors related to arrays and provides examples of code implementations.

Uploaded by

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

SRM INSTITUTE OF SCIENCE & TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

18CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Mr. [Link] M.E., (Ph.D.,)


Assistant Professor (Sr. G)
Department of Computer Science and Engineering,
SRM IST, Chennai.
UNIT III ARRAY, STRING & FUNCTIONS
3.1 ARRAY:-
1. Initializing and accessing of 2D Array
2. Initializing multidimensional Array – Array programs 2D
3. Array contiguous memory – Array advantages and Limitations
4. Array construction for real-time application common programming errors
3.2 STRING:-
1. String Basics – String Declaration and Initialization
2. String Functions: gets(), puts(), getchar(), putchar(), printf()
3. String Functions: atoi, strlen, strcat strcmp
4. String Functions: sprintf, sscanf, strrev, strcpy, strstr, strtok
5. Arithmetic characters on strings.
3.3 FUNCTIONS:-
1. Functions declaration and definition : Types: Call by Value, Call by Reference
2. Function with and without Arguments and no Return values
3. Functions with and without Arguments and Return Values
4. Passing Array to function with return type
5. Recursion Function
3.1 ARRAY
3.1.1. Initializing and accessing of 2D Array

ACCESSING OF 2D ARRAY:-
•Two Dimensional Array requires Two Subscript Variables
•Two Dimensional Array stores the values in the form of matrix.
•One Subscript Variable denotes the “Row” of a matrix.
•Another Subscript Variable denotes the “Column” of a matrix.

INITIALIZING OF 2D ARRAY:
An array of two dimensions can be declared as follows:
data_type array_name[size1][size2];
Here data_type is the name of some type of data, such as int. Also, size1 and
size2 are sizes of the array’s first and second dimensions respectively.
3.1 ARRAY
3.1.1. Initializing and accessing of 2D Array
3.1 ARRAY
3.1.1. Initializing and accessing of 2D Array
// Program to take 5 values from the user and store
them in an array Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
Enter 5 integers: 25
// taking input and storing it in an array
32
for(int i = 0; i < 5; ++i) {
56
scanf("%d", &values[i]);
65
}
45
printf("Displaying integers: ");
Displaying integers: 25
// printing elements of an array
32
for(int i = 0; i < 5; ++i) {
56
printf("%d\n", values[i]);
65
}
45
return 0;
}
3.2 2D- ARRAY
3.1.1. Initializing and accessing of 2D Array
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
3.2 2D- ARRAY
3.1.1. Initializing and accessing of 2D Array
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n"); // Displaying the sum
for (int i = 0; i < 2; ++i) printf("\nSum Of Matrix:");
for (int j = 0; j < 2; ++j) for (int i = 0; i < 2; ++i)
{ for (int j = 0; j < 2; ++j)
printf("Enter b%d%d: ", i + 1, j + 1); {
scanf("%f", &b[i][j]); printf("%.1f\t", result[i][j]);
}
// adding corresponding elements of two arrays if (j == 1)
for (int i = 0; i < 2; ++i) printf("\n");
for (int j = 0; j < 2; ++j) }
{ return 0;
result[i][j] = a[i][j] + b[i][j]; }
}
3.2 2D- ARRAY
3.1.1. Initializing and accessing of 2D Array

/tmp/euz2KSsyII.o
Enter elements of 1st matrix
Enter a11: 1
Enter a12: 3
Enter a21: 5
Enter a22: 7
Enter elements of 2nd matrix
Enter b11: 2
Enter b12: 4
Enter b21: 6
Enter b22: 8

Sum Of Matrix:3.0 7.0


11.0 15.0
TWO DIMENSIONAL ARRAYS FOR INTER FUNCTION COMMUNICATION
2D Array for Inter Function Communication

Passing individual elements Passing a row Passing the entire 2D array

There are three ways of passing parts of the two dimensional array to a function. First, we can pass
individual elements of the array. This is exactly same as we passed element of a one dimensional
array.
main()
Passing a row
{
int arr[2][3]= ( {1, 2, 3}, {4, 5, 6} };
func(arr[1]);
}
void func(int arr[])
{
int i;
for(i=0;i<5;i++)
printf("%d", arr[i] * 10);
}

Passing the entire 2D array


To pass a two dimensional array to a function, we use the array name as the actual parameter.
(The same we did in case of a 1D array). However, the parameter in the called function must
indicate that the array has two dimensions.
3.2 MULTIDIMENSIONAL - ARRAY
• A multi dimensional array is an array of arrays.

• Like we have one index in a single dimensional array, two indices in a two dimensional array, in the same way we
have n indices in a n-dimensional array or multi dimensional array.

• Conversely, an n dimensional array is specified using n indices.

• An n dimensional m1 x m2 x m3 x ….. mn array is a collection m1*m2*m3* ….. *mn elements.

• In a multi dimensional array, a particular element is specified by using n subscripts as A[I1][I2][I3]…[In], where,
I1<=M1 I2<=M2 I3 <= M3 ……… In <= Mn
3.2 MULTIDIMENSIONAL - ARRAY
#include<stdio.h> { printf(“\n\n”);
int main() for(j=0;j<2;j++)
{ int array1[3][3][3], i, j, k; {
printf(“\n Enter the elements of the matrix”); printf(“\n”);
printf(“\n ******************************”); for(k=0;k<2;k++)
for(i=0;i<2;i++) printf(“\t array[%d][ %d][ %d] =
%d”, i, j, k, array1[i][j][k]);
{ for(j=0;j<2;j++)
}
{ for(k=0;k<2;k++)
}
{
}
printf(“\n array[%d][
%d][ %d] = ”, i, j, k);
scanf(“%d”,
&array1[i][j][k]);
}
}
}
printf(“\n The matrix is : “);
printf(“\n *********************************”)l
for(i=0;i<2;i++)
3.3 Array contiguous memory – Array advantages and
Limitations
 When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block or continuous memory.
 Alternate meaning of Contiguous Memory is Suppose inside memory we have reserved
1000-1200 memory addresses for special purposes then we can say that these 200
blocks are going to reserve contiguousmemory.
 Using static array declaration, alloc() / malloc() function to allocate big chunk of memory
dynamically.

ContiguousMemory Allocation: Two registers are used while implementing the


contiguous memory scheme. Theseregisters are base register and limit register.
3.3 Array contiguous memory – Array advantages and Limitations

When OS is executing a process inside the main memory then


content of each register are as–

 Register - Content of register.


 Base register- Starting address of the location where process execution ishappening.

Limit register- Total amount of memory in bytes consumed by process.


When process try to refer a part of the memory then it will firstly refer the base address from base register
and then it will refer relative address of memory location with respect to base address
3.3 Array contiguous memory – Array advantages and Limitations
1. Advantages:
 It is better and convenient way of storing the data of same datatype with samesize.
 It allows us to store known number of elements in it.
 It allocates memory in contiguous memory locations for its elements. It does not
allocate any extra space/ memory for its elements. Hence there is no memory overflow
or shortage of memory in arrays.
 Iterating the arrays using their index is faster compared to any other methods like linked
listetc.
 It allows to store the elements in any dimensional array - supports multidimensional
array.
2. Limitations of Array:
• Static Data and Can hold data belonging to same Data types
• Inserting data and Deletion Operation in Array is Difficult
• Bound Checking, Shortage and Wastage of Memory.
3.4 Array construction for real-time application
common programming errors
(i) Constant Expression Require
#include<stdio.h> void main()
{
int i=10; int a[i];
}
In this example we see what’s that error?
According to array concept, we are allocating memory for array at
compile time so if the size of array is going to vary then how it is possible
to allocate memory to an array.

i is initialized to 10 and using a[i] does not mean a[10] because ‘i’ is
Integer Variable whose value can be changed inside program
3.4 Array construction for real-time application
common programming errors
 Value of Const Variable Cannot be changed
 we know that value of Const Variable cannotbe changed once initialized
so we can write above example as below –
Ex:
#include<stdio.h>
void main()
{
const int i=10; int a[i];
}
or
int a[10];
3.4 Array construction for real-time application
common programming errors
(ii) Empty Valued 1D Array
#include<stdio.h>
void main() • Size of 1D Array should be
Specified as a Constant Value.
{ #include<stdio.h>
int arr[]; void main()
} {
Instead of it Write it as– int a[] = {};/ / This also
#include<stdio.h> void main() Cause an Error
{ }
int a[] ={1,1};
}
3.4 Array construction for real-time application
common programming errors
(iii) 1D Array with no
Bound Checking
#include<stdio.h>
void main()
{
int a[5];
printf("%d",a[7]);
}
Here Array size specified is 5.
If the maximum size of array is “MAX” then we can access following elements of an
array –
Elements accessible for Array Size "MAX" =arr[0]
=.
= arr[MAX-1]
3.4 Array construction for real-time application
common programming errors
4. CaseSensitive
#include<stdio.h>
void main()
{
int a[5]; printf("%d",A[2]);
}
Array Variable is Case Sensitive so A[2] does not print anything it
Displays Error Message : “Undefined SymbolA“
3.2 STRING:-
1. String Basics, Declaration and Initialization
 Stringsin Care representedbyarraysof characters.
 String is nothing but the collection of the individual array elements or characters stored at contiguous memory locations
i) Character array –'P','P','S'
ii) Double quotes - “PPS"is aexample of String.
 If string contains the double quote as part of string then we can use escape character to keep double quote as a part of
string.
 “PPS" is aexample of String.
iii) Null Character: char name[10] ={'P','P','S','\0'}
 The end of the string is marked with a special character, the null character, which is a character all of whose bits are
zero i.e.,a NULL.. String always Terminated with NULLCharacter (‘/0′)
 NULLCharacter is having ASCII value 0, ASCII Value of '\0' =0
 As String is nothing but an array , so it is Possible toAccess Individual Character
name[10] ="PPS";
 It is possible to access individualcharacter name[0] ='P';
name[1] ='P';
name[2] ='S';
name[3] ='\0';
3.2 STRING:-
1. String Basics, Declaration and Initialization
iv) MEMORY
EachCharacter Occupy 1 byte of Memory
Sizeof "PPS" = Sizeof 'P' +
= Sizeof 'P' +
= Size of 'S' ; Sizeof "PPS” is 3 BYTES
EachCharacter is stored in consecutive memorylocation.
Address of 'P' =2000 Address of 'P' =2001 Address of 'S' =2002
3.2 STRING:-
1. String Declaration and Initialization
 String Declaration:
 String data type is not supported in C Programming. String means Collection of
Characters to form particular word. String is useful whenever we accept name of the
person, Address of the person, some descriptive information. We cannot declare
string using String Data Type, instead of we use array of type character to create
String.
 Character Array is Called as‘String’.
 Character Array is Declared Before Using it inProgram.

char String_Variable_name [ SIZE] ;


Eg: char city[30];
3.2 STRING:-
1. String Declaration and Initialization
Point Explanation

Significance - We have declared array of character[[Link]]

Size of string - 30Bytes

Bound checking - CDoes not Support Bound Checking i.e if we store City
with size greater than 30 then Cwill not give you any error

Data type - char

Maximum size - 30
3.2 STRING:-
1. String Declaration and Initialization
Precautions to be taken while declaring Character Variable :
 String / Character Array Variable name should be legal CIdentifier.
 String Variable must have Sizespecified.
 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 asC++/ Java. Cdoes not support String datatype
 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>
3.2 STRING:-
1. String Initialization
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 CProgramming –
1)Initializing Unsized Array of Character
2)Initializing String Directly
3)Initializing String Using Character Pointer
3.2 STRING:-
1. String Initialization
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'};
3.2 STRING:-
1. String Initialization
Way 2 : Directly initialize String Variable
 In this method we are directly assigning String tovariable by writing text in doublequotes.
 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";

Way 3 : Character Pointer Variable


 Declare Character variable of pointer type sothat it can hold the baseaddressof “String”
 Base address means address of first array element i.e (addressof name[0] )
 NULLCharacter is appendedAutomatically
 char *name ="PPS";
3.2 STRING:-
1. String Initialization
Example:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritche
Your name is Dennis.
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()

 gets()  strcmp()
 puts()  sprintf()
 getchar()  sscanf()
 putchar()  strrev()
 printf()  strcpy()
 atoi()  strstr()
 strlen()  strtok()
 strcat ()
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
[Link]():
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);
}
Output:
Enter the name: programming inc
Note:-
%sis not Required
Spaces are allowed in gets()
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
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.
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Example :
#include< stdio.h>
#include< conio.h>
void main()
{
char string[] = "This is an example string\n";
puts(string);
puts("String");
getch();
}
Output :
String is : This is an example string
String is : String
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
3. 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 untilthe user presses return. (i.e Enter Key)

Syntax for Accepting String and Working :


/ * getchar accepts character & stores in ch * /
char ch = getchar();
 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’.
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Parameter Explanation

Header File - stdio.h


Return Type - int (ASCII Value of the character)
Parameter - Void
Use - Accepting the Character
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Example 1 :
In the following example we are just accepting the single character and
printing it on theconsole –
main()
{
char ch;
ch = getchar();
printf("Accepted Character : %c",ch);
}
Output :
Accepted Character : A
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
4. PUTCHAR():Displaying String in CProgramming
Syntax : int putchar(int c);
Way 1 : Taking Character as Parameter putchar('a') ; / / Displays :a
 Individual Character is Given as parameter to this function.

 We have to explicitly mention Character.

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.

Way3:Displaying Particular Character fromArray:-putchar(a[0]) ;/ / Display a[0] th element


from array
 CharacterArray or String consists of collection of characters.

 Like accessing individual array element , characters can be displayed one by

one using putchar().


3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Example:
#include< stdio.h> #include< conio.h> int main()
{
char string[] = "C programming\n"; int i=0;
while(string[i]!='\0')
{
putchar(string[i]); i++;
}
return 0;
}
Output:
Cprogramming
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
5 P R I N T F ( ):

Syntax :
Way 1 : Messaging
printf (" Type your Message / Instruction " ) ;
Way 2 : Display String
printf ("Name of Person is %s", name ) ;
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
3.3 String ( ): atoi, strlen, strcat and strcmp()

ATOI FUNCTION

 Atoi =Ato I =Alphabet to Integer


 Convert String of number into Integer

Example:
#include <stdio.h>
int main() Value = 100
{
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n", value);
return 0;
}
3.3 String ( ): atoi, strlen, strcat and strcmp()

Significance :
 Can Convert any String of Number into Integer Value that can Perform

the arithmetic Operations like integer


 Header File : stdlib.h

Ways of Using Atoi Function :


Way 1 : Passing Variable in Atoi Function
int num;
char marks[3] ="98"; num = atoi(marks);
printf("\nMarks : %d",num);

Way 2 : Passing Direct String in Atoi Function int num;


num = atoi("98");
printf("\nMarks : %d",num);
3.3 String ( ): atoi, strlen, strcat and strcmp()
Significance :
 Can Convert any String of Number into Integer Value that can Perform

the arithmetic Operations like integer


 Header File : stdlib.h

Ways of Using Atoi Function :


Way 1 : Passing Variable in Atoi Function
int num;
char marks[3] ="98";
num = atoi(marks);
printf("\nMarks : %d",num);

Way 2 : Passing Direct String in Atoi Function


int num;
num = atoi("98");
printf("\nMarks : %d",num);
3.3 String ( ): atoi, strlen, strcat and strcmp()
STRLENFUNCTION:

 Finding length of string

Point Explanation

No of Parameters - 1
Parameter Taken - Character Array Or String
Return Type - Integer
Description - Compute the Length of theString
Header file - string.h
3.3 String ( ): atoi, strlen, strcat and strcmp()
Different Ways of Using strlen():
 There are different ways of using strlen function. We can pass

different parameters to strlen()function.


• “%zu” format, z is a length modifier and u stand for unsigned type.

Way 1 : Taking String Variable as Parameter


char str[20];
int length ;
printf("\nEnter the String :"); gets(str);
length = strlen(str);
printf("\nLength of String : %d ", length);
Output:
Enter the String : hello
Length of String : 5
3.3 String ( ): atoi, strlen, strcat and strcmp()

Way 2 : Taking String Variable which is Already Initialized usingPointer char *str =
"priteshtaral";
int length ;
length = strlen(str);
printf("\nLength of String : %d ", length);

Way 3 : Taking Direct String int length ;


length = strlen("pritesh"); printf("\nLength of String :
%d",length);

Way 4 : Writing Function in printf Statement char *str ="pritesh";


printf("\nLength of String : %d",strlen(str));
3.3 String ( ): atoi, strlen, strcat and strcmp()
STRCATFUNCTION:
What strcat Actually does?
 Function takes 2 Strings / Character Array as Parameter
 Appends second string at the end ofFirst String.
 Parameter Taken - 2 Character Arrays / Strings
 Return Type - Character Array / String

Syntax :
char* strlen ( char * s1, char * s2);
3.3 String ( ): atoi, strlen, strcat and strcmp()
Ways of Using Strcat Function :
Way 1 : Taking String Variable asParameter
char str1[20] = “Don” , str2[20] = “Bosqo”;
strcat(str1,str2);
puts(str1);

Way 2 : Taking String Variable which is Already Initialized usingPointer


char *str1 = “Ind”,*str2 =“ia”;
strcat(str1,str2);/ / Result stored in str1 puts(str1); / / Result : India

Way 3 : Writing Function in printf Statement


printf(“nString: “, strcat(“Ind”,”ia”));
3.3 String ( ): atoi, strlen, strcat and strcmp()

STRCMPFUNCTION:

What strcmp Actually Does?


 Function takes two Strings asparameter.

 It returns integer.

Syntax : int strcmp ( char *s1, char *s2 ) ;

Return Type Condition


-ve Value - String1 <String2
+ve Value - String1 >String2
0 Value - String1 =String2
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example 1 : Two strings are Equal char s1[10] =
"SAM",s2[10]="SAM" ;
int len;
len = strcmp (s1,s2); Output
0
/* So the output will be 0. if u want to print the string then give condition like*/
char s1[10] = "SAM",s2[10]="SAM" ;
int len;
len = strcmp (s1,s2); if (len ==0)
printf ("Two Strings areEqual");
Output:
Two Strings are Equal
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example 2 : String1 is Greater thanString2

char s1[10] = "SAM",s2[10]="sam" ;


int len;
len = strcmp (s1,s2);
printf ("%d",len); //-ve value
Output:
-32

Reason :
ASCII value of “SAM” is smaller than“sam”
ASCII value of ‘S’ is smaller than ‘s’
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example 3 : String1 is Smaller than String1

char s1[10] = "sam",s2[10]="SAM" ; int len;


len = strcmp (s1,s2);
printf ("%d",len); //+ve value
Output:
85

Reason :
ASCII value of “SAM” is greater than“sam”
ASCII value of ‘S’ is greater than ‘s’
3.4 String Functions: sprintf, sscanf, strrev, strcpy,
strstr and strtok
SPRINTFFUNCTION:
 sends formatted output to String.

Features :
 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’.

 Main Per pose : Sending Formatted output toString.

 Header File : Stdio.h

Syntax :
int sprintf(char *buf,char format,arg_list);
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

Example :
int age = 23 ;
char str[100];
sprintf( str , "My age is %d",age); puts(str);
Output:
My age is 23
Analysis of Source Code:Just keep in mind that
 Assume that we are using printf then we get output “My age is 23”
 What does printf does ? —–Just Print the Result on theScreen
 Similarly Sprintf stores result “My age is 23” into string str instead of printing it.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

SSCANF( ):
Syntax :
int sscanf(const char *buffer, const char *format[, address, ...]);

What it actually does?


 Data is read from array Pointed to by buffer rather than stdin.
 Return Type is Integer
 Return value is nothing but number of fields that were actually assigned a value
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

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;
}
Output:
Name : Fresh2refresh Age : 5
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

STRSTRFUNCTION:
 Finds first occurrence of sub-string in other string
Features :
 Finds the first occurrence of a sub string in another string
 Main Purpose : FindingSubstring
 Header File : String.h
 Checks whether s2 is present in s1 or not
 On success, strstr returns a pointer to the element in s1 wheres2 begins (points to s2
in s1).
 On error (if s2 does not occur in s1), strstr returns null.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

Syntax:
char *strstr(const char *s1, constchar *s2);
#include <stdio.h> #include <string.h> int main()
{
char string[55] ="This is a test string; char *p;
p = strstr (string,"test"); if(p)
{
printf("string found\n");
printf("First string \"test\" in\"%s\" to"\" \"%s \"" ,string, p);
}
else
printf("string not found\n"); return 0;
}

Output:
string found
First string “test” in “This is atest string” to “test string”.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

STRREV():
 reverses a given string in Clanguage. Syntax for strrev( ) function is

given below.
char *strrev(char *string);
 strrev() function is nonstandard function which may not available in

standard library inC.


Algorithm to Reverse String in C:
 Start

 Take 2 Subscript Variables ‘i’,’j’

 ‘j’ is Positioned on LastCharacter

 ‘i’ is positioned on firstcharacter

 str[i] is interchanged with str[j]

 Increment ‘i’

 Decrement ‘j’

 If ‘i’ > ‘j’then goto step 3

 Stop
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

Example
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] ="Hello";
printf("String before strrev() :%s\n",name);
printf("String after strrev(%s",strrev(name));
return 0;
}
Output:
String before strrev() :Hello
String after strrev() : olleH
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

STRCPYFUNCTION:
Copy second string into First

What strcmp Actually Does?


 Function takes two Strings asparameter.

 Header File : String.h.

 It returns string.

 Purpose : Copies String2 into String1.

 Original contents of String1 will be lost.

 Original contents of String2 will remains as it is.

Syntax :
char * strcpy ( char *string1, char *string2 );
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

 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.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

Example:
char s1[10] = "SAM" ;
char s2[10] = "MIKE" ;
strcpy (s1,s2);

puts (s1);

puts (s2);

Output: MIKE MIKE


3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

Example 2 #include <stdio.h>


#include <string.h>
int main( )
{
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;
}
Output
source string =hihello
target string =
target string after strcpy( ) =hihello
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

STRTOKFUNCTION:
 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 moretokens.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok

#include <stdio.h>
#include <string.h>
int main()
Output: Problem
{
Solving
char str[] ="Problem_Solving_in_c";
in
char* token =strtok(str, "_");
C
while (token != NULL)
{
printf("%s\n", token);
token =strtok(NULL, "_");
}
return 0;
}
3.5 Arithmetic characters on strings.
ARITHMETIC CHARACTERSON STRING
 CProgramming Allows you to Manipulate onString
 Whenever the Character is variable is used in the expression then it is
automatically Converted into Integer Value called ASCIIvalue.
 All Characters can be Manipulated Value.(Addition,Subtraction)

Examples :
ASCII value of : ‘a’ is 97
ASCII value of : ‘z’ is 121
3.5 Arithmetic characters on strings.

Way 1:Displays ASCII value[ Note that %d inPrintf]


char x = 'a';
printf("%d",x); / / Display Result= 97
Way 2 :Displays Character value[Note that %cin Printf] char x = 'a';

printf("%c",x); / / DisplayResult = a
Way 3 : Displays Next ASCII value[ Note that %d in Printf ] char x = 'a' + 1 ;

printf("%d",x); //Display Result = 98 (ascii of 'b' )


3.5 Arithmetic characters on strings.
Way 4 Displays Next Character value[Note that %cin Printf ]
char x = 'a' + 1;
printf("%c",x); / / Display Result= 'b‘

Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ] char x = 'z' - 'a';

printf("%d",x);/*Display Result = 25 (difference between ASCII of z and a ) * /

Way 6 : Displays Difference between 2 ASCII in Char [Note that %cin Printf ]
char x = 'z' - 'a';
printf("%c",x);/*Display Result =( difference between ASCII of z and a ) * /
3.3 FUNCTIONS:-

3.2 STRING:-
1. String Basics – String Declaration and Initialization
2. String Functions: gets(), puts(), getchar(), putchar(), printf()
3. String Functions: atoi, strlen, strcat strcmp
4. String Functions: sprintf, sscanf, strrev, strcpy, strstr, strtok
5. Arithmetic characters on strings.
3.3 FUNCTIONS:-
1. Functions declaration and definition : Types: Call by Value, Call by Reference
2. Function with and without Arguments and no Return values
3. Functions with and without Arguments and Return Values
4. Passing Array to function with return type
5. Recursion Function
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
FUNCTION DECLARATIONANDDEFINITION:
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The Cstandard library provides numerous built-in functions that your program can call. For example,
strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and
many more functions.
 Afunction can also be referred asa method or a sub-routine or a procedure,
etc.
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
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.
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
main()
{
display(); • We have written functions in the above
}
void mumbai() specified sequence , however functions
{
printf("In mumbai");
are called in which order we call them.
}
void pune()
{
india();
} •Here functions are called this
void display() sequence –
{
pune(); • main() display() pune()
}
void india() india() mumbai().
{
mumbai();
}
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
Why Funtion is used???

Advantages of Writing Function in CProgramming

1. Modular and Structural Programming can be done


 We can divide c program in smaller modules.
We can call module whenever require. e.g suppose we have written calculator program then we can write 4
modules (i.e add,sub,multiply,divide)
 Modular programming makes Cprogram more readable.
 Modules once created , can be re-used in other programs.

2. It follows Top-Down Execution approach , Somain can be kept very small.


 Every Cprogram starts from mainfunction.
 Every function is called directly or indirectly through main
 Example : Top down approach. (functions are executed from top to bottom)
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
Individual functions can be easily built,tested
 As we have developed Capplication in modules we can test each andevery
module.
 Unit testing is possible.
 Writing code in function will enhance application developmentprocess.
Program development become easy
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.
Afunction can call other functions & alsoitself
 Function can call other function.
 Function can call itself , which is called as “recursive” function.
 Recursive functions are also useful in order to write systemfunctions.
It is easier to understand the Programtopic
 We can get overall idea of the project just by reviewing function names.
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference

How Function works in CProgramming?


 Cprogramming is modular programminglanguage.
We must divide Cprogram in the different modules in order to create
more readable, eye catching ,effective, optimized code.
 In this article we are going to see how functionis Cprogramming works ?
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference

TYPESOFCALLING
While creating a C function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform
the defined task.
When a program calls a function, the program control is transferred to the called function. A called function
performs a defined task and when its

return statement is executed or when its function-ending closing brace is


reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the
function returns a value, then you can store the returned value. For example −
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
#include <stdio.h>
int max(int num1, intnum2);
int main ()
{
output
/ * local variable definition * / int a = 100;
Max value is : 200
int b =200;
int ret; / * calling a function to get max value * /
ret = max(a, b);
printf( "Max value is : %d\n", ret);
return 0;
} / * function returning the max between two numbers * /
int max(int num1, int num2)
{ / * local variable declaration * /
int result;
if (num1 >num2)
result = num1;
else
result = num2;
return result;
}
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
Call by value This method 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.
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 This method 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. This means that changes made to the parameter affect
the argument.
void swap (int x, int y) /* function definition to swap the values */
{
int temp; temp =*x;
*x = *y;
*y = temp;
return;
}
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
#include <stdio.h>
void swap(int x, int y);
/* function declaration */
int main () Output:
{ Before swap, value of a :100
int a = 100; /* local variable definition */ Before swap, value of b :200
int b = 200; After swap, value of a :200
printf("Before swap, value of a : %d\n", a ); After swap, value of b :100
printf("Before swap, value of b : %d\n", b );
/*calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
3.3.2. Function with arguments and with Return values

// fun with arg with return values


#include <stdio.h>
int checkPrimeNumber(int n); // int is returned from the function
int main() int checkPrimeNumber(int n)
{ { Output:
int n, flag; int i; /tmp/RzMt7SJQqb.o
printf("Enter a positive integer: "); Enter a positive integer: 353
scanf("%d",&n); for(i=2; i <= n/2; ++i)
flag = checkPrimeNumber(n); { is a prime number
if(flag == 1) if(n%i == 0)
printf("%d is not a prime number",n); return 1;
else }
printf("%d is a prime number",n); return 0;
return 0; }
}
3.3.3. Function with and no Return values

// with arg with no return


#include <stdio.h> // return type is void meaning
void checkPrimeAndDisplay(int n); doesn't return any value
void checkPrimeAndDisplay(int n)
int main() {
int i, flag = 0; Output:
{ /tmp/RzMt7SJQqb.o
int n;
for(i=2; i <= n/2; ++i) Enter a positive integer: 353
printf("Enter a positive integer: "); {
if(n%i == 0){ is a prime number
scanf("%d",&n);
flag = 1;
// n is passed to the function break;
checkPrimeAndDisplay(n); }
}
return 0; if(flag == 1)
} printf("%d is not a prime
number.",n);
else
printf("%d is a prime
number.", n);
}
3.3.4. Function with no arguments and with Return values

//no arguments with return value


#include <stdio.h>
int getInteger();
int main()
{ // returns integer entered by the
int n, i, flag = 0; user
// no argument is passed int getInteger()
n = getInteger(); {
for(i=2; i<=n/2; ++i) int n;
{ Output:
if(n%i==0){ printf("Enter a positive integer: /tmp/RzMt7SJQqb.o
flag = 1; ");
break; Enter a positive integer: 353
scanf("%d",&n);
} is a prime number
} return n;
if (flag == 1) }
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
3.3.4. Function with no arguments and no Return values

// no arg no return value // return type is void meaning doesn't return any value
#include <stdio.h> void checkPrimeNumber()
void checkPrimeNumber(); {
int main() int n, i, flag = 0;
{ printf("Enter a positive integer: ");
checkPrimeNumber(); // argument is not passed scanf("%d",&n);
return 0; for(i=2; i <= n/2; ++i)
} {
if(n%i == 0)
{
flag = 1;
Output: }
/tmp/RzMt7SJQqb.o }
if (flag == 1)
Enter a positive integer: 353 printf("%d is not a prime number.", n);
is a prime number else
printf("%d is a prime number.", n);
}
DECLARATION INITIALAIZATION

ARRAY
TYPES OF MULTI
ARRAY
-D

SINGLE 2-D
D
Insert the Sub Title of Your Presentation

You might also like