SlideShare ist ein Scribd-Unternehmen logo
1 von 86
SRM INSTITUTE OF SCIENCE & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Mr. P.Gowsikraja M.E., (Ph.D.,)
Assistant Professor (Sr. G)
Department of Computer Science and Engineering,
SRM IST, Chennai.
18CSS101J – PROGRAMMING FOR PROBLEM SOLVING
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: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%dn", values[i]);
}
return 0;
}
Enter 5 integers: 25
32
56
65
45
Displaying integers: 25
32
56
65
45
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 matrixn");
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 matrixn");
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]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("nSum Of Matrix:");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("%.1ft", result[i][j]);
if (j == 1)
printf("n");
}
return 0;
}
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
Passing individual elements Passing a row
2D Array for Inter Function Communication
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.
Passing a row main()
{
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>
int main()
{ int array1[3][3][3], i, j, k;
printf(“n Enter the elements of the matrix”);
printf(“n ******************************”);
for(i=0;i<2;i++)
{ 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++)
{ printf(“nn”);
for(j=0;j<2;j++)
{
printf(“n”);
for(k=0;k<2;k++)
printf(“t array[%d][ %d][ %d] =
%d”, i, j, k, array1[i][j][k]);
}
}
}
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 MemoryBlock 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.
ContiguousMemoryAllocation: 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 eachregister are as–
 Register - Content of register.
 Baseregister- Starting address of the location where processexecution ishappening.
Limit register- Totalamount of memory in bytes consumedby 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 addressof memorylocation with respectto baseaddress
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 usto 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 ofArray:
• 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) ConstantExpressionRequire
#include<stdio.h> void main()
{
int i=10; int a[i];
}
In this example we seewhat’s that error?
According to array concept, we are allocating memory for array at
compile time soif the sizeof 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
 Valueof ConstVariable Cannotbe changed
 we know that value of ConstVariable cannotbe changed once initialized
sowe canwrite above example asbelow –
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) EmptyValued1DArray
#include<stdio.h>
void main()
{
int arr[];
}
Insteadof it Write it as–
#include<stdio.h> void main()
{
int a[] ={1,1};
}
• Size of 1D Array should be
Specified asaConstant Value.
#include<stdio.h>
void main()
{
int a[] = {};// This also
Cause anError
}
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]);
}
HereArray sizespecified is 5.
If the maximum size of array is “MAX” then we canaccessfollowing elements of an
array –
Elements accessiblefor 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
DisplaysError Message : “Undefined SymbolA“
3.2 STRING:-
1.String Basics, Declaration and Initialization
 StringsinCarerepresentedbyarraysof characters.
 Stringisnothing but the collection of the individualarray elements or charactersstored at contiguousmemory locations
i) Character array –'P','P','S'
ii) Double quotes - “PPS"isaexampleof String.
 If string contains the double quote aspart of string then we can use escape character to keep double quote asapart of
string.
 “PPS"isaexampleof String.
iii) Null Character: char name[10] ={'P','P','S','0'}
 Theend of the string is marked with aspecial character, the null character, which is acharacter all of whose bits are
zeroi.e.,aNULL..String always Terminated with NULLCharacter (‘/0′)
 NULLCharacter is havingASCIIvalue 0,ASCIIValueof '0' =0
 AsString is nothing but an array , soit is PossibletoAccessIndividual Character
name[10] ="PPS";
 It is possible to accessindividualcharacter name[0] ='P';
name[1] ='P';
name[2] ='S';
name[3] ='0';
3.2 STRING:-
1.String Basics, Declaration and Initialization
iv) MEMORY
EachCharacterOccupy1byte of Memory
Sizeof "PPS"=Sizeof 'P' +
=Sizeof 'P' +
=Sizeof 'S'; Sizeof "PPS”is3BYTES
EachCharacterisstored in consecutive memorylocation.
Addressof 'P' =2000 Addressof 'P' =2001 Addressof '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.
 CharacterArray is Called as‘String’.
 CharacterArray 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 - Wehavedeclared array of character[i.eString]
Sizeof string - 30Bytes
Boundchecking - CDoesnot Support Bound Checkingi.e if we store City
with size greater than 30 then Cwill not give you any error
Datatype - char
Maximum size - 30
3.2 STRING:-
1.String Declaration and Initialization
Precautions to be taken while declaring Character Variable :
 String / CharacterArray Variable name should be legal CIdentifier.
 String Variable must have Sizespecified.
 charcity[];
 Above Statement will causecompile timeerror.
 Do not use String as data type because String data type is included in
later languages suchasC++/ Java.Cdoes not support String datatype
 Stringcity;
 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 waysof initializing String in CProgramming –
1)Initializing UnsizedArray 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 isAutomatically calculated byCompiler
 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 StringVariable
 In this method we aredirectly assigningStringtovariable bywriting 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 bythecompiler.
 charname[ ] ="PPS";
Way 3 :Character PointerVariable
 DeclareCharactervariable of pointer type sothat it can hold the baseaddressof “String”
 Base address means address of first array element i.e (addressof name[0])
 NULLCharacterisappendedAutomatically
 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()
 puts()
 getchar()
 putchar()
 printf()
 atoi()
 strlen()
 strcat ()
 strcmp()
 sprintf()
 sscanf()
 strrev()
 strcpy()
 strstr()
 strtok()
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
1.GETS():
Syntaxfor AcceptingString:
char * gets ( char * str ); OR gets(<variable-name>)
Example: #include<stdio.h>
void main()
{
char name[20];
printf("nEnter the Name:");
gets(name);
}
Output:
Enterthe name:programming inc
Note:-
%sis not Required
Spacesare allowed in gets()
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
2. PUTS():
Way1 :Messaging
 puts(" Typeyour Message/ Instruction ");
 LikePrintf Statement puts() canbe used todisplay message.
Way2 : Display String
 puts(string_Variable_name) ;
Notesor Facts:
 puts is included in header file“stdio.h”
 Asname suggestit 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 examplestringn";
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()
 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 seethe characters untilthe user pressesreturn. (i.e Enter Key)
SyntaxforAcceptingStringandWorking :
/* getchar accepts character & stores in ch */
charch= getchar();
3. 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
- stdio.h
- int (ASCIIValue of thecharacter)
- Void
- Accepting the Character
Header File
ReturnType
Parameter
Use
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Example1 :
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 :
AcceptedCharacter:A
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
4. PUTCHAR():Displaying String in CProgramming
Syntax : int putchar(int c);
Way1 : TakingCharacter asParameter putchar('a') ; // Displays :a
 Individual Character is Given asparameter to this function.
 Wehave to explicitly mention Character.
Way2 : TakingVariable asParameter:-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 usingputchar().
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Example:
#include< stdio.h> #include< conio.h> int main()
{
char string[] ="Cprogrammingn"; int i=0;
while(string[i]!='0')
{
putchar(string[i]); i++;
}
return 0;
}
Output:
Cprogramming
3.2 String Functions: gets(), puts(), getchar(),
putchar(), printf()
Syntax:
Way1 : Messaging
printf (" Type your Message/ Instruction " ) ;
Way2 : DisplayString
printf ("Name of Personis %s", name );
Notes or Facts:
printf is included in header file“stdio.h”
Asname suggest it used for Printingor DisplayingMessagesor Instructions Uses:
 Printing Message
 Askuser for entering the data ( Labels. Instructions)
 Printing Results
5 PRINTF( ):
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example:
#include <stdio.h>
int main()
{
char a[10] = "100";
int value = atoi(a);
printf("Value = %dn", value);
return 0;
}
 Atoi =Ato I =Alphabet to Integer
 ConvertStringof numberinto Integer
ATOI FUNCTION
Value = 100
Significance :
 CanConvert any String of Number into Integer Valuethat can Perform
the arithmetic Operations likeinteger
 Header File : stdlib.h
Waysof UsingAtoi Function :
Way1 : PassingVariable in Atoi Function
int num;
char marks[3] ="98"; num =atoi(marks);
printf("nMarks : %d",num);
Way2 : PassingDirect String in AtoiFunction int num;
num =atoi("98");
printf("nMarks : %d",num);
3.3 String ( ): atoi, strlen, strcat and strcmp()
Significance :
 CanConvert any String of Number into Integer Valuethat can Perform
the arithmetic Operations likeinteger
 Header File : stdlib.h
Waysof UsingAtoi Function :
Way1 : PassingVariable in Atoi Function
int num;
char marks[3] ="98";
num =atoi(marks);
printf("nMarks : %d",num);
Way2 : PassingDirect String in AtoiFunction
int num;
num =atoi("98");
printf("nMarks : %d",num);
3.3 String ( ): atoi, strlen, strcat and strcmp()
STRLENFUNCTION:
No of Parameters
ParameterTaken
Return Type
Description
Header file
- 1
- CharacterArray OrString
- Integer
- Compute the Length of theString
- string.h
 Findinglength of string
Point Explanation
3.3 String ( ): atoi, strlen, strcat and strcmp()
Different Ways of Using strlen():
 There are different waysof using strlen function. Wecan 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()
Way2 : TakingString Variable which isAlready Initialized usingPointer char *str =
"priteshtaral";
int length;
length =strlen(str);
printf("nLength of String : %d",length);
Way3 : TakingDirect String int length;
length =strlen("pritesh"); printf("nLength of String :
%d",length);
Way4 : Writing Function in printfStatement char *str ="pritesh";
printf("nLength of String : %d",strlen(str));
3.3 String ( ): atoi, strlen, strcat and strcmp()
STRCATFUNCTION:
What strcatActually does?
 Function takes 2 Strings / CharacterArray asParameter
 Appends second string at the end ofFirst String.
 ParameterTaken- 2 CharacterArrays / Strings
 Return Type - CharacterArray / String
Syntax:
char* strlen ( char* s1,char* s2);
3.3 String ( ): atoi, strlen, strcat and strcmp()
Ways of Using Strcat Function:
Way1 : TakingString Variable asParameter
char str1[20] =“Don” , str2[20]=“Bosqo”;
strcat(str1,str2);
puts(str1);
Way2 : TakingString Variable which isAlready Initialized usingPointer
char *str1 =“Ind”,*str2 =“ia”;
strcat(str1,str2);// Result stored in str1 puts(str1); // Result : India
Way3 : Writing Function in printf Statement
printf(“nString: “, strcat(“Ind”,”ia”));
3.3 String ( ): atoi, strlen, strcat and strcmp()
STRCMPFUNCTION:
What strcmpActually Does?
 Function takestwo Stringsasparameter.
 It returns integer.
Syntax: int strcmp( char *s1, char*s2 ) ;
ReturnType
-ve Value
+veValue
0 Value
Condition
- String1 <String2
- String1 >String2
- String1 =String2
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example1 : Twostrings 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:
TwoStrings are Equal
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example2 : String1 is Greater thanString2
char s1[10] ="SAM",s2[10]="sam" ;
int len;
len =strcmp (s1,s2);
printf ("%d",len); //-vevalue
Output:
-32
Reason :
ASCIIvalue of “SAM” is smaller than“sam”
ASCIIvalue of ‘S’is smaller than‘s’
3.3 String ( ): atoi, strlen, strcat and strcmp()
Example3 : String1 is Smaller thanString1
char s1[10] ="sam",s2[10]="SAM" ; int len;
len =strcmp (s1,s2);
printf ("%d",len); //+vevalue
Output:
85
Reason :
ASCIIvalue of “SAM” is greater than“sam”
ASCIIvalue of ‘S’is greater than‘s’
3.3 String ( ): atoi, strlen, strcat and strcmp()
3.4 String Functions: sprintf, sscanf, strrev, strcpy,
strstr and strtok
SPRINTFFUNCTION:
 sendsformatted 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 Perpose : Sending Formatted output toString.
 Header File : Stdio.h
Syntax:
int sprintf(char *buf,char format,arg_list);
Example:
int age=23;
charstr[100];
sprintf( str , "Myageis%d",age); puts(str);
Output:
My ageis23
Analysisof SourceCode:Justkeepin mind that
 Assumethat we areusingprintf then we get output “My ageis23”
 What doesprintf does?—–JustPrint the Resulton theScreen
 Similarly Sprintf storesresult “My ageis23” into string str instead of printingit.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
SSCANF( ):
Syntax:
int sscanf(constchar*buffer, constchar*format[, address, ...]);
What it actually does?
 Data is read from array Pointed to by buffer rather than stdin.
 Return Typeis Integer
 Return value is nothing but number of fields that were actually assigned avalue
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 : %sn Age:%dn",name,age); return 0;
}
Output:
Name: Fresh2refreshAge: 5
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
STRSTRFUNCTION:
 Findsfirst occurrenceof sub-stringin other string
Features :
 Finds the first occurrence of asub string in another string
 Main Purpose : FindingSubstring
 Header File : String.h
 Checkswhether s2is present in s1or not
 Onsuccess,strstr returns apointer to the element in s1wheres2 begins (points to s2
ins1).
 Onerror (if s2does 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] ="Thisisateststring; char *p;
p =strstr(string,"test"); if(p)
{
printf("string foundn");
printf("First string "test" in"%s" to"" "%s "" ,string,p);
}
else
printf("string not foundn"); return 0;
}
Output:
stringfound
Firststring“test” in “This isatest string” to “test string”.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
STRREV():
 reversesagivenstring in Clanguage.Syntaxfor strrev( ) function is
givenbelow.
char*strrev(char *string);
 strrev() function isnonstandard function which maynot available in
standard library inC.
Algorithmto ReverseStringinC:
 Start
 Take2SubscriptVariables ‘i’,’j’
 ‘j’ isPositioned on LastCharacter
 ‘i’ ispositioned on firstcharacter
 str[i] isinterchanged withstr[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() :%sn",name);
printf("String after strrev(%s",strrev(name));
return 0;
}
Output:
String before strrev() :Hello
Stringafter strrev() : olleH
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
STRCPYFUNCTION:
Copysecondstringinto First
What strcmpActually Does?
 Function takes two Strings asparameter.
 Header File : String.h.
 It returnsstring.
 Purpose : CopiesString2 into String1.
 Original contents of String1 willbe lost.
 Original contents of String2 will remains asit 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 sourcestringvalue
won’t becopiedinto destination string.
 For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from sourcestring
will be copied into destination string and remaining 10
characters won’t be copied and willbe 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
Example2 #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
sourcestring =hihello
target string=
target string after strcpy( ) =hihello
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
STRTOKFUNCTION:
 tokenizes/parses the givenstringusing delimiter.
Syntax
char* strtok ( char * str, constchar * 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 NULLwhen there are no moretokens.
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
#include <stdio.h>
#include<string.h>
int main()
{
char str[] ="Problem_Solving_in_c";
char* token =strtok(str, "_");
while (token != NULL)
{
printf("%sn", token);
token =strtok(NULL,"_");
}
return0;
}
Output: Problem
Solving
in
C
3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
3.5 Arithmetic characters on strings.
ARITHMETICCHARACTERSONSTRING
 CProgrammingAllows you to Manipulate onString
 Whenever the Character is variable is used in the expression then it is
automatically Converted into Integer Valuecalled ASCIIvalue.
 All Characters can be Manipulated Value.(Addition,Subtraction)
Examples:
ASCIIvalueof : ‘a’is97
ASCIIvalueof : ‘z’is 121
3.5 Arithmetic characters on strings.
Way1:DisplaysASCIIvalue[ Note that %dinPrintf]
char x='a';
printf("%d",x); // Display Result=97
Way2 :Displays Character value[Note that %cin Printf] char x='a';
printf("%c",x); // DisplayResult=a
Way3 : Displays NextASCIIvalue[ Note that %din Printf ] char x='a' +1 ;
printf("%d",x); //Display Result =98 (ascii of 'b' )
3.5 Arithmetic characters on strings.
Way4 Displays Next Character value[Note that %cin Printf ]
char x='a' +1;
printf("%c",x); // Display Result='b‘
Way5 : Displays Difference between 2ASCIIin Integer[Note %din Printf ] char x='z' - 'a';
printf("%d",x);/*Display Result =25 (difference between ASCIIof zand a)*/
Way6 : Displays Difference between 2ASCIIin Char[Note that %cin Printf ]
char x='z' - 'a';
printf("%c",x);/*Display Result=( difference between ASCIIof zand 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
FUNCTIONDECLARATIONANDDEFINITION:
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 candefine 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 aspecifictask.
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 canalso be referred asamethod or asub-routine or aprocedure,
etc.
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
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();
}
void mumbai()
{
printf("In mumbai");
}
void pune()
{
india();
}
void display()
{
pune();
}
void india()
{
mumbai();
}
• We have written functions in the above
specified sequence , however functions
are called in which order we callthem.
•Here functions are called this
sequence –
• main() display() pune()
india() mumbai().
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
WhyFuntionisused???
Advantagesof WritingFunctionin CProgramming
1. Modular andStructuralProgrammingcanbe done
 Wecandivide cprogram in smaller modules.
Wecancall module whenever require. e.g suppose we have written calculator program then we canwrite 4
modules (i.eadd,sub,multiply,divide)
 Modular programming makesCprogrammorereadable.
 Modules once created , canbere-usedin other programs.
2. It followsTop-DownExecutionapproach, Somaincanbekept verysmall.
 EveryCprogram starts from mainfunction.
 Everyfunction is called directly or indirectlythroughmain
 Example : Topdownapproach.(functions are executed from top to bottom)
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
Individual functionscanbeeasily built,tested
 Aswe have developed Capplication in modules we cantest eachandevery
module.
 Unit testingis possible.
 Writing code in function will enhanceapplicationdevelopmentprocess.
Programdevelopmentbecome easy
Frequentlyusedfunctionscanbeput together in the customized library
 Wecanput frequently used functions in our customheaderfile.
After creating header file we canre useheader file. Wecaninclude header file in other program.
Afunctioncancallother functions& alsoitself
 Function cancall other function.
 Function cancall itself , which is called as“recursive” function.
 Recursive functions are also useful in order to write systemfunctions.
It iseasier to understandthe Programtopic
 Wecanget overall idea of the project just by reviewing functionnames.
3.3.1 FUNCTIONS:- Functions declaration and definition :
Types: Call by Value, Call by Reference
HowFunctionworksin CProgramming?
 Cprogramming is modular programminglanguage.
Wemust divide Cprogram in the different modules in order to create
more readable, eye catching ,effective, optimizedcode.
 In this article we are going to seehow 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()
{
/* local variable definition */ int a=100;
int b =200;
int ret; /* calling afunction to get maxvalue */
ret =max(a, b);
printf( "Max value is : %dn", ret);
return 0;
} /* function returning the maxbetween two numbers */
int max(int num1, intnum2)
{ /* local variable declaration */
int result;
if (num1 >num2)
result =num1;
else
result =num2;
return result;
}
output
Max value is : 200
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 theargument.
void swap (int x, int y)
{
int temp;
temp =x; /* savethe 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 ()
{
int a = 100; /* local variable definition */
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/*calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
3.3.2. Function with arguments and with Return values
Output:
/tmp/RzMt7SJQqb.o
Enter a positive integer: 353
is a prime number
// fun with arg with return values
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
flag = checkPrimeNumber(n);
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// int is returned from the function
int checkPrimeNumber(int n)
{
int i;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}
return 0;
}
3.3.3. Function with and no Return values
Output:
/tmp/RzMt7SJQqb.o
Enter a positive integer: 353
is a prime number
// with arg with no return
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the function
checkPrimeAndDisplay(n);
return 0;
}
// return type is void meaning
doesn't return any value
void checkPrimeAndDisplay(int n)
{
int i, flag = 0;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0){
flag = 1;
break;
}
}
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
Output:
/tmp/RzMt7SJQqb.o
Enter a positive integer: 353
is a prime number
//no arguments with return value
#include <stdio.h>
int getInteger();
int main()
{
int n, i, flag = 0;
// no argument is passed
n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// returns integer entered by the
user
int getInteger()
{
int n;
printf("Enter a positive integer:
");
scanf("%d",&n);
return n;
}
3.3.4. Function with no arguments and no Return values
Output:
/tmp/RzMt7SJQqb.o
Enter a positive integer: 353
is a prime number
// no arg no return value
#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // argument is not passed
return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeNumber()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
INITIALAIZATIONDECLARATION
TYPES OF
ARRAY
ARRAY
MULTI
- D
2-D
SINGLE
D
Insert the Sub Title of Your Presentation

Weitere ähnliche Inhalte

Was ist angesagt?

C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control StructureMohammad Shaker
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehmanNauman Rehman
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsMohammad Shaker
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 

Was ist angesagt? (20)

C tech questions
C tech questionsC tech questions
C tech questions
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
 
Pointers
PointersPointers
Pointers
 
C++11
C++11C++11
C++11
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 

Ähnlich wie Unit 3

Ähnlich wie Unit 3 (20)

Unit 3
Unit 3 Unit 3
Unit 3
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
arrays
arraysarrays
arrays
 
Array
ArrayArray
Array
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
Array i imp
Array  i impArray  i imp
Array i imp
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
 
memory allocation by Novodita
memory allocation by Novoditamemory allocation by Novodita
memory allocation by Novodita
 
memory allocation.pptx
memory allocation.pptxmemory allocation.pptx
memory allocation.pptx
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 

Kürzlich hochgeladen

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Kürzlich hochgeladen (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Unit 3

  • 1. SRM INSTITUTE OF SCIENCE & TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Mr. P.Gowsikraja M.E., (Ph.D.,) Assistant Professor (Sr. G) Department of Computer Science and Engineering, SRM IST, Chennai. 18CSS101J – PROGRAMMING FOR PROBLEM SOLVING
  • 2. 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. 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.
  • 4. 3.1 ARRAY 3.1.1. Initializing and accessing of 2D Array
  • 5. 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: "); // taking input and storing it in an array for(int i = 0; i < 5; ++i) { scanf("%d", &values[i]); } printf("Displaying integers: "); // printing elements of an array for(int i = 0; i < 5; ++i) { printf("%dn", values[i]); } return 0; } Enter 5 integers: 25 32 56 65 45 Displaying integers: 25 32 56 65 45
  • 6. 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 matrixn"); 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]); }
  • 7. 3.2 2D- ARRAY 3.1.1. Initializing and accessing of 2D Array // Taking input using nested for loop printf("Enter elements of 2nd matrixn"); 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]); } // adding corresponding elements of two arrays for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { result[i][j] = a[i][j] + b[i][j]; } // Displaying the sum printf("nSum Of Matrix:"); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { printf("%.1ft", result[i][j]); if (j == 1) printf("n"); } return 0; }
  • 8. 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
  • 9. TWO DIMENSIONAL ARRAYS FOR INTER FUNCTION COMMUNICATION Passing individual elements Passing a row 2D Array for Inter Function Communication 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. Passing a row main() { 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.
  • 10. 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
  • 11. 3.2 MULTIDIMENSIONAL - ARRAY #include<stdio.h> int main() { int array1[3][3][3], i, j, k; printf(“n Enter the elements of the matrix”); printf(“n ******************************”); for(i=0;i<2;i++) { 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++) { printf(“nn”); for(j=0;j<2;j++) { printf(“n”); for(k=0;k<2;k++) printf(“t array[%d][ %d][ %d] = %d”, i, j, k, array1[i][j][k]); } } }
  • 12. 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 MemoryBlock 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. ContiguousMemoryAllocation: Two registers are used while implementing the contiguous memory scheme.Theseregisters are base register and limit register.
  • 13. 3.3 Array contiguous memory – Array advantages and Limitations When OS is executing a process inside the main memory then content of eachregister are as–  Register - Content of register.  Baseregister- Starting address of the location where processexecution ishappening. Limit register- Totalamount of memory in bytes consumedby 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 addressof memorylocation with respectto baseaddress
  • 14. 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 usto 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 ofArray: • 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.
  • 15. 3.4 Array construction for real-time application common programming errors (i) ConstantExpressionRequire #include<stdio.h> void main() { int i=10; int a[i]; } In this example we seewhat’s that error? According to array concept, we are allocating memory for array at compile time soif the sizeof 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
  • 16. 3.4 Array construction for real-time application common programming errors  Valueof ConstVariable Cannotbe changed  we know that value of ConstVariable cannotbe changed once initialized sowe canwrite above example asbelow – Ex: #include<stdio.h> void main() { const int i=10; int a[i]; } or int a[10];
  • 17. 3.4 Array construction for real-time application common programming errors (ii) EmptyValued1DArray #include<stdio.h> void main() { int arr[]; } Insteadof it Write it as– #include<stdio.h> void main() { int a[] ={1,1}; } • Size of 1D Array should be Specified asaConstant Value. #include<stdio.h> void main() { int a[] = {};// This also Cause anError }
  • 18. 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]); } HereArray sizespecified is 5. If the maximum size of array is “MAX” then we canaccessfollowing elements of an array – Elements accessiblefor Array Size"MAX" =arr[0] =. =arr[MAX-1]
  • 19. 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 DisplaysError Message : “Undefined SymbolA“
  • 20. 3.2 STRING:- 1.String Basics, Declaration and Initialization  StringsinCarerepresentedbyarraysof characters.  Stringisnothing but the collection of the individualarray elements or charactersstored at contiguousmemory locations i) Character array –'P','P','S' ii) Double quotes - “PPS"isaexampleof String.  If string contains the double quote aspart of string then we can use escape character to keep double quote asapart of string.  “PPS"isaexampleof String. iii) Null Character: char name[10] ={'P','P','S','0'}  Theend of the string is marked with aspecial character, the null character, which is acharacter all of whose bits are zeroi.e.,aNULL..String always Terminated with NULLCharacter (‘/0′)  NULLCharacter is havingASCIIvalue 0,ASCIIValueof '0' =0  AsString is nothing but an array , soit is PossibletoAccessIndividual Character name[10] ="PPS";  It is possible to accessindividualcharacter name[0] ='P'; name[1] ='P'; name[2] ='S'; name[3] ='0';
  • 21. 3.2 STRING:- 1.String Basics, Declaration and Initialization iv) MEMORY EachCharacterOccupy1byte of Memory Sizeof "PPS"=Sizeof 'P' + =Sizeof 'P' + =Sizeof 'S'; Sizeof "PPS”is3BYTES EachCharacterisstored in consecutive memorylocation. Addressof 'P' =2000 Addressof 'P' =2001 Addressof 'S'=2002
  • 22. 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.  CharacterArray is Called as‘String’.  CharacterArray is Declared Before Using it inProgram. char String_Variable_name [ SIZE]; Eg:char city[30];
  • 23. 3.2 STRING:- 1.String Declaration and Initialization Point Explanation Significance - Wehavedeclared array of character[i.eString] Sizeof string - 30Bytes Boundchecking - CDoesnot Support Bound Checkingi.e if we store City with size greater than 30 then Cwill not give you any error Datatype - char Maximum size - 30
  • 24. 3.2 STRING:- 1.String Declaration and Initialization Precautions to be taken while declaring Character Variable :  String / CharacterArray Variable name should be legal CIdentifier.  String Variable must have Sizespecified.  charcity[];  Above Statement will causecompile timeerror.  Do not use String as data type because String data type is included in later languages suchasC++/ Java.Cdoes not support String datatype  Stringcity;  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>
  • 25. 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 waysof initializing String in CProgramming – 1)Initializing UnsizedArray of Character 2)Initializing String Directly 3)Initializing String Using Character Pointer
  • 26. 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 isAutomatically calculated byCompiler  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'};
  • 27. 3.2 STRING:- 1.String Initialization Way 2 :Directly initialize StringVariable  In this method we aredirectly assigningStringtovariable bywriting 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 bythecompiler.  charname[ ] ="PPS"; Way 3 :Character PointerVariable  DeclareCharactervariable of pointer type sothat it can hold the baseaddressof “String”  Base address means address of first array element i.e (addressof name[0])  NULLCharacterisappendedAutomatically  char*name ="PPS";
  • 28. 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.
  • 29. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf()  gets()  puts()  getchar()  putchar()  printf()  atoi()  strlen()  strcat ()  strcmp()  sprintf()  sscanf()  strrev()  strcpy()  strstr()  strtok()
  • 30. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() 1.GETS(): Syntaxfor AcceptingString: char * gets ( char * str ); OR gets(<variable-name>) Example: #include<stdio.h> void main() { char name[20]; printf("nEnter the Name:"); gets(name); } Output: Enterthe name:programming inc Note:- %sis not Required Spacesare allowed in gets()
  • 31. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() 2. PUTS(): Way1 :Messaging  puts(" Typeyour Message/ Instruction ");  LikePrintf Statement puts() canbe used todisplay message. Way2 : Display String  puts(string_Variable_name) ; Notesor Facts:  puts is included in header file“stdio.h”  Asname suggestit used for Printing or Displaying Messages or Instructions.
  • 32. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() Example : #include< stdio.h> #include< conio.h> void main() { char string[] ="This is an examplestringn"; puts(string); puts("String"); getch(); } Output : String is :This is an example string String is :String
  • 33. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf()  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 seethe characters untilthe user pressesreturn. (i.e Enter Key) SyntaxforAcceptingStringandWorking : /* getchar accepts character & stores in ch */ charch= getchar(); 3. 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’.
  • 34. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() Parameter Explanation - stdio.h - int (ASCIIValue of thecharacter) - Void - Accepting the Character Header File ReturnType Parameter Use
  • 35. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() Example1 : 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 : AcceptedCharacter:A
  • 36. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() 4. PUTCHAR():Displaying String in CProgramming Syntax : int putchar(int c); Way1 : TakingCharacter asParameter putchar('a') ; // Displays :a  Individual Character is Given asparameter to this function.  Wehave to explicitly mention Character. Way2 : TakingVariable asParameter:-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 usingputchar().
  • 37. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() Example: #include< stdio.h> #include< conio.h> int main() { char string[] ="Cprogrammingn"; int i=0; while(string[i]!='0') { putchar(string[i]); i++; } return 0; } Output: Cprogramming
  • 38. 3.2 String Functions: gets(), puts(), getchar(), putchar(), printf() Syntax: Way1 : Messaging printf (" Type your Message/ Instruction " ) ; Way2 : DisplayString printf ("Name of Personis %s", name ); Notes or Facts: printf is included in header file“stdio.h” Asname suggest it used for Printingor DisplayingMessagesor Instructions Uses:  Printing Message  Askuser for entering the data ( Labels. Instructions)  Printing Results 5 PRINTF( ):
  • 39. 3.3 String ( ): atoi, strlen, strcat and strcmp() Example: #include <stdio.h> int main() { char a[10] = "100"; int value = atoi(a); printf("Value = %dn", value); return 0; }  Atoi =Ato I =Alphabet to Integer  ConvertStringof numberinto Integer ATOI FUNCTION Value = 100
  • 40. Significance :  CanConvert any String of Number into Integer Valuethat can Perform the arithmetic Operations likeinteger  Header File : stdlib.h Waysof UsingAtoi Function : Way1 : PassingVariable in Atoi Function int num; char marks[3] ="98"; num =atoi(marks); printf("nMarks : %d",num); Way2 : PassingDirect String in AtoiFunction int num; num =atoi("98"); printf("nMarks : %d",num); 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 41. Significance :  CanConvert any String of Number into Integer Valuethat can Perform the arithmetic Operations likeinteger  Header File : stdlib.h Waysof UsingAtoi Function : Way1 : PassingVariable in Atoi Function int num; char marks[3] ="98"; num =atoi(marks); printf("nMarks : %d",num); Way2 : PassingDirect String in AtoiFunction int num; num =atoi("98"); printf("nMarks : %d",num); 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 42. STRLENFUNCTION: No of Parameters ParameterTaken Return Type Description Header file - 1 - CharacterArray OrString - Integer - Compute the Length of theString - string.h  Findinglength of string Point Explanation 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 43. Different Ways of Using strlen():  There are different waysof using strlen function. Wecan 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()
  • 44. Way2 : TakingString Variable which isAlready Initialized usingPointer char *str = "priteshtaral"; int length; length =strlen(str); printf("nLength of String : %d",length); Way3 : TakingDirect String int length; length =strlen("pritesh"); printf("nLength of String : %d",length); Way4 : Writing Function in printfStatement char *str ="pritesh"; printf("nLength of String : %d",strlen(str)); 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 45. STRCATFUNCTION: What strcatActually does?  Function takes 2 Strings / CharacterArray asParameter  Appends second string at the end ofFirst String.  ParameterTaken- 2 CharacterArrays / Strings  Return Type - CharacterArray / String Syntax: char* strlen ( char* s1,char* s2); 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 46. Ways of Using Strcat Function: Way1 : TakingString Variable asParameter char str1[20] =“Don” , str2[20]=“Bosqo”; strcat(str1,str2); puts(str1); Way2 : TakingString Variable which isAlready Initialized usingPointer char *str1 =“Ind”,*str2 =“ia”; strcat(str1,str2);// Result stored in str1 puts(str1); // Result : India Way3 : Writing Function in printf Statement printf(“nString: “, strcat(“Ind”,”ia”)); 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 47. STRCMPFUNCTION: What strcmpActually Does?  Function takestwo Stringsasparameter.  It returns integer. Syntax: int strcmp( char *s1, char*s2 ) ; ReturnType -ve Value +veValue 0 Value Condition - String1 <String2 - String1 >String2 - String1 =String2 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 48. Example1 : Twostrings 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: TwoStrings are Equal 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 49. Example2 : String1 is Greater thanString2 char s1[10] ="SAM",s2[10]="sam" ; int len; len =strcmp (s1,s2); printf ("%d",len); //-vevalue Output: -32 Reason : ASCIIvalue of “SAM” is smaller than“sam” ASCIIvalue of ‘S’is smaller than‘s’ 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 50. Example3 : String1 is Smaller thanString1 char s1[10] ="sam",s2[10]="SAM" ; int len; len =strcmp (s1,s2); printf ("%d",len); //+vevalue Output: 85 Reason : ASCIIvalue of “SAM” is greater than“sam” ASCIIvalue of ‘S’is greater than‘s’ 3.3 String ( ): atoi, strlen, strcat and strcmp()
  • 51. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok SPRINTFFUNCTION:  sendsformatted 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 Perpose : Sending Formatted output toString.  Header File : Stdio.h Syntax: int sprintf(char *buf,char format,arg_list);
  • 52. Example: int age=23; charstr[100]; sprintf( str , "Myageis%d",age); puts(str); Output: My ageis23 Analysisof SourceCode:Justkeepin mind that  Assumethat we areusingprintf then we get output “My ageis23”  What doesprintf does?—–JustPrint the Resulton theScreen  Similarly Sprintf storesresult “My ageis23” into string str instead of printingit. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 53. SSCANF( ): Syntax: int sscanf(constchar*buffer, constchar*format[, address, ...]); What it actually does?  Data is read from array Pointed to by buffer rather than stdin.  Return Typeis Integer  Return value is nothing but number of fields that were actually assigned avalue 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 54. Example #include<stdio.h> int main() { char buffer[30]="Fresh2refresh 5"; char name[20]; int age; sscanf(buffer,"%s %d",name,&age); printf ("Name : %sn Age:%dn",name,age); return 0; } Output: Name: Fresh2refreshAge: 5 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 55. STRSTRFUNCTION:  Findsfirst occurrenceof sub-stringin other string Features :  Finds the first occurrence of asub string in another string  Main Purpose : FindingSubstring  Header File : String.h  Checkswhether s2is present in s1or not  Onsuccess,strstr returns apointer to the element in s1wheres2 begins (points to s2 ins1).  Onerror (if s2does not occur in s1), strstr returns null. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 56. Syntax: char*strstr(const char*s1, constchar*s2); #include <stdio.h> #include<string.h> int main() { char string[55] ="Thisisateststring; char *p; p =strstr(string,"test"); if(p) { printf("string foundn"); printf("First string "test" in"%s" to"" "%s "" ,string,p); } else printf("string not foundn"); return 0; } Output: stringfound Firststring“test” in “This isatest string” to “test string”. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 57. STRREV():  reversesagivenstring in Clanguage.Syntaxfor strrev( ) function is givenbelow. char*strrev(char *string);  strrev() function isnonstandard function which maynot available in standard library inC. Algorithmto ReverseStringinC:  Start  Take2SubscriptVariables ‘i’,’j’  ‘j’ isPositioned on LastCharacter  ‘i’ ispositioned on firstcharacter  str[i] isinterchanged withstr[j]  Increment‘i’  Decrement‘j’  If ‘i’ >‘j’then goto step 3  Stop 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 58. Example #include<stdio.h> #include<string.h> int main() { char name[30] ="Hello"; printf("String before strrev() :%sn",name); printf("String after strrev(%s",strrev(name)); return 0; } Output: String before strrev() :Hello Stringafter strrev() : olleH 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 59. STRCPYFUNCTION: Copysecondstringinto First What strcmpActually Does?  Function takes two Strings asparameter.  Header File : String.h.  It returnsstring.  Purpose : CopiesString2 into String1.  Original contents of String1 willbe lost.  Original contents of String2 will remains asit is. Syntax: char* strcpy( char*string1, char*string2 ); 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 60.  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 sourcestringvalue won’t becopiedinto destination string.  For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from sourcestring will be copied into destination string and remaining 10 characters won’t be copied and willbe truncated. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 61. 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
  • 62. Example2 #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 sourcestring =hihello target string= target string after strcpy( ) =hihello 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 63. STRTOKFUNCTION:  tokenizes/parses the givenstringusing delimiter. Syntax char* strtok ( char * str, constchar * 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 NULLwhen there are no moretokens. 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 64. #include <stdio.h> #include<string.h> int main() { char str[] ="Problem_Solving_in_c"; char* token =strtok(str, "_"); while (token != NULL) { printf("%sn", token); token =strtok(NULL,"_"); } return0; } Output: Problem Solving in C 3.4 String Functions: sprintf, sscanf, strrev, strcpy, strstr and strtok
  • 65. 3.5 Arithmetic characters on strings. ARITHMETICCHARACTERSONSTRING  CProgrammingAllows you to Manipulate onString  Whenever the Character is variable is used in the expression then it is automatically Converted into Integer Valuecalled ASCIIvalue.  All Characters can be Manipulated Value.(Addition,Subtraction) Examples: ASCIIvalueof : ‘a’is97 ASCIIvalueof : ‘z’is 121
  • 66. 3.5 Arithmetic characters on strings. Way1:DisplaysASCIIvalue[ Note that %dinPrintf] char x='a'; printf("%d",x); // Display Result=97 Way2 :Displays Character value[Note that %cin Printf] char x='a'; printf("%c",x); // DisplayResult=a Way3 : Displays NextASCIIvalue[ Note that %din Printf ] char x='a' +1 ; printf("%d",x); //Display Result =98 (ascii of 'b' )
  • 67. 3.5 Arithmetic characters on strings. Way4 Displays Next Character value[Note that %cin Printf ] char x='a' +1; printf("%c",x); // Display Result='b‘ Way5 : Displays Difference between 2ASCIIin Integer[Note %din Printf ] char x='z' - 'a'; printf("%d",x);/*Display Result =25 (difference between ASCIIof zand a)*/ Way6 : Displays Difference between 2ASCIIin Char[Note that %cin Printf ] char x='z' - 'a'; printf("%c",x);/*Display Result=( difference between ASCIIof zand a) */
  • 68. 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
  • 69. FUNCTIONDECLARATIONANDDEFINITION: 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 candefine 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 aspecifictask. 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 canalso be referred asamethod or asub-routine or aprocedure, etc. 3.3.1 FUNCTIONS:- Functions declaration and definition : Types: Call by Value, Call by Reference
  • 70. 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.
  • 71. 3.3.1 FUNCTIONS:- Functions declaration and definition : Types: Call by Value, Call by Reference main() { display(); } void mumbai() { printf("In mumbai"); } void pune() { india(); } void display() { pune(); } void india() { mumbai(); } • We have written functions in the above specified sequence , however functions are called in which order we callthem. •Here functions are called this sequence – • main() display() pune() india() mumbai().
  • 72. 3.3.1 FUNCTIONS:- Functions declaration and definition : Types: Call by Value, Call by Reference WhyFuntionisused??? Advantagesof WritingFunctionin CProgramming 1. Modular andStructuralProgrammingcanbe done  Wecandivide cprogram in smaller modules. Wecancall module whenever require. e.g suppose we have written calculator program then we canwrite 4 modules (i.eadd,sub,multiply,divide)  Modular programming makesCprogrammorereadable.  Modules once created , canbere-usedin other programs. 2. It followsTop-DownExecutionapproach, Somaincanbekept verysmall.  EveryCprogram starts from mainfunction.  Everyfunction is called directly or indirectlythroughmain  Example : Topdownapproach.(functions are executed from top to bottom)
  • 73. 3.3.1 FUNCTIONS:- Functions declaration and definition : Types: Call by Value, Call by Reference Individual functionscanbeeasily built,tested  Aswe have developed Capplication in modules we cantest eachandevery module.  Unit testingis possible.  Writing code in function will enhanceapplicationdevelopmentprocess. Programdevelopmentbecome easy Frequentlyusedfunctionscanbeput together in the customized library  Wecanput frequently used functions in our customheaderfile. After creating header file we canre useheader file. Wecaninclude header file in other program. Afunctioncancallother functions& alsoitself  Function cancall other function.  Function cancall itself , which is called as“recursive” function.  Recursive functions are also useful in order to write systemfunctions. It iseasier to understandthe Programtopic  Wecanget overall idea of the project just by reviewing functionnames.
  • 74. 3.3.1 FUNCTIONS:- Functions declaration and definition : Types: Call by Value, Call by Reference HowFunctionworksin CProgramming?  Cprogramming is modular programminglanguage. Wemust divide Cprogram in the different modules in order to create more readable, eye catching ,effective, optimizedcode.  In this article we are going to seehow functionis Cprogramming works ?
  • 75. 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 −
  • 76. 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() { /* local variable definition */ int a=100; int b =200; int ret; /* calling afunction to get maxvalue */ ret =max(a, b); printf( "Max value is : %dn", ret); return 0; } /* function returning the maxbetween two numbers */ int max(int num1, intnum2) { /* local variable declaration */ int result; if (num1 >num2) result =num1; else result =num2; return result; } output Max value is : 200
  • 77. 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 theargument. void swap (int x, int y) { int temp; temp =x; /* savethe 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; }
  • 78. 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 () { int a = 100; /* local variable definition */ int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /*calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100
  • 79. 3.3.2. Function with arguments and with Return values Output: /tmp/RzMt7SJQqb.o Enter a positive integer: 353 is a prime number // fun with arg with return values #include <stdio.h> int checkPrimeNumber(int n); int main() { int n, flag; printf("Enter a positive integer: "); scanf("%d",&n); flag = checkPrimeNumber(n); if(flag == 1) printf("%d is not a prime number",n); else printf("%d is a prime number",n); return 0; } // int is returned from the function int checkPrimeNumber(int n) { int i; for(i=2; i <= n/2; ++i) { if(n%i == 0) return 1; } return 0; }
  • 80. 3.3.3. Function with and no Return values Output: /tmp/RzMt7SJQqb.o Enter a positive integer: 353 is a prime number // with arg with no return #include <stdio.h> void checkPrimeAndDisplay(int n); int main() { int n; printf("Enter a positive integer: "); scanf("%d",&n); // n is passed to the function checkPrimeAndDisplay(n); return 0; } // return type is void meaning doesn't return any value void checkPrimeAndDisplay(int n) { int i, flag = 0; for(i=2; i <= n/2; ++i) { if(n%i == 0){ flag = 1; break; } } if(flag == 1) printf("%d is not a prime number.",n); else printf("%d is a prime number.", n); }
  • 81. 3.3.4. Function with no arguments and with Return values Output: /tmp/RzMt7SJQqb.o Enter a positive integer: 353 is a prime number //no arguments with return value #include <stdio.h> int getInteger(); int main() { int n, i, flag = 0; // no argument is passed n = getInteger(); for(i=2; i<=n/2; ++i) { if(n%i==0){ flag = 1; break; } } if (flag == 1) printf("%d is not a prime number.", n); else printf("%d is a prime number.", n); return 0; } // returns integer entered by the user int getInteger() { int n; printf("Enter a positive integer: "); scanf("%d",&n); return n; }
  • 82. 3.3.4. Function with no arguments and no Return values Output: /tmp/RzMt7SJQqb.o Enter a positive integer: 353 is a prime number // no arg no return value #include <stdio.h> void checkPrimeNumber(); int main() { checkPrimeNumber(); // argument is not passed return 0; } // return type is void meaning doesn't return any value void checkPrimeNumber() { int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i <= n/2; ++i) { if(n%i == 0) { flag = 1; } } if (flag == 1) printf("%d is not a prime number.", n); else printf("%d is a prime number.", n); }
  • 84.
  • 85.
  • 86. Insert the Sub Title of Your Presentation