Unit 3arraystringfunctions 201219064627
Unit 3arraystringfunctions 201219064627
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
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);
}
• 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.
• 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.
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.
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
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
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 :
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
Printing Results
3.3 String ( ): atoi, strlen, strcat and strcmp()
ATOI FUNCTION
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
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
Way 2 : Taking String Variable which is Already Initialized usingPointer char *str =
"priteshtaral";
int length ;
length = strlen(str);
printf("\nLength of String : %d ", length);
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);
STRCMPFUNCTION:
It returns integer.
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
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.
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, ...]);
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
Increment ‘i’
Decrement ‘j’
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
It returns string.
Syntax :
char * strcpy ( char *string1, char *string2 );
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);
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.
#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.
printf("%c",x); / / DisplayResult = a
Way 3 : Displays Next ASCII value[ Note that %d in Printf ] char x = 'a' + 1 ;
Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ] char x = 'z' - '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???
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
// 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