SlideShare a Scribd company logo
Arrays & Strings
Definition of Array
An array is a fixed – size sequenced collection of elements of the
same data type. It is simply a grouping of like – type data. In its
simplest form, an array can be used to represent a list of numbers, or
list of names. (OR)
“A set of consecutive storage location referred by a single name to
store homogeneous data type.”
int A[10]
Array is a Collection of Homogenous Data Items Example
1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test Scores of a class of students. 12/6/2020 2
1. One Dimensional Array.
2. Two Dimensional Array.
3. Multi Dimensional Array
Types of Array
One Dimensional Array
12/6/2020 4
X
Y
Z
One Dimensional Array is defined any one of axis (X or Y or Z) in the graph
Arrays
So far, we've been declaring simple variables
int i;
It is also possible to declare an array of Several elements. an array is a
variable that can hold more than one value , The declaration
int a[10];
declares an array, named a, consisting of ten elements, each of type int.
We can represent the array a above with a picture like this:
12/6/2020 5
•Arrays are zero-based: the ten elements of a 10-element array are
numbered from 0 to 9.
• An array uses a single identifier, together with an integer
index, to create one variable that can hold many values
• An array is created the same as a “normal” variable, but with
the addition of square brackets indicating the size of the array
• Each value in the array is called an element
12/6/2020 6
Arrays
One Dimensional Arrays
Syntax data_type array_name[size];
Description Data_type valid data type in C language
Array_name name given to the array
Size are the size of the dimensions
Example int a[3];
float b[4];
12/6/2020 7
Initializing Arrays
• An array is initialized using a code block containing
comma-delimited values which match in position the
elements in the array
• If there are values in the initialization block, but not enough
to fill the array, all the elements in the array without values
are initialized to 0 in the case of float or int, and NULL in
the case of char
• If there are values in the initialization block, an explicit size
for the array does not need to be specified, only an empty
Array Element Operator is needed. C will count the values
and size the array for you.
12/6/2020 8
Initializing Arrays
int x [ 5 ] = { 1,2,3,4,5 }; size 10 bytes
creates array with elements 0-4 values 1-5
int x [ 5 ] = { 4,3 }; size 10 bytes
creates array with elements 0-4 values 4,3,0,0,0
int x [ ] = { 1,2,3 }; size 6 bytes
creates array with elements 0-2 values 1,2,3
char c [ 4 ] = { ‘M’ , ‘o’ , ‘o’ }; size 4 bytes
creates array with elements 0-3 values M o o NULL
12/6/2020 9
Arrays
•The first element of the array is x[0], the second element is x[1]..
e.g x[0] = 10; x[1] = 20; x[2] = 30 x[3] = 40 x[4] = 50
Total = 150;
This loop sets all ten elements of the array a to 0.
int a[i]; int i;
for(i = 0; i < 10; i = i + 1)
a[i] = 0;
To copy the contents of one array to another, you must again do so
one by one:
int b[10];
for(i = 0; i < 10; i = i + 1)
b[i] = a[i];
Printing Array Values
for(i = 0; i < 10; i = i + 1)
printf("%dn", a[i]);
12/6/2020 10
Array Basics
• An array has a fixed number of elements based on its creation
• The elements are ALWAYS numbered from 0 to 1 less than the array’s size
• Referencing an element outside of the created bounds is possible but not
recommended
12/6/2020 11
Visual Representation of an Array
12/6/2020 12
Identifier?
?
23
?
int x[4];
x[2]=23;
342901
342903
342905
342917
0
1
2
3
X
Address
Offset
Value
The Array Element Operator [ ]
• The Array Element Operator is used to reference a specific
array element
• The expression inside the Array Element must resolve to
type int. This value is known as an index
• The value of the index can be any number, but care should
be taken that the index falls within the bounds of the array.
The bounds of an array are defined as 0 to 1 less than the
size of the array
12/6/2020 13
Array Example
#include <stdio.h>
int main(void)
{
int x[5];
x[0]=23; valid
x[2.3]=5; invalid: index is not an int
x[6]=45; valid but not recommended
return 0;
}
12/6/2020 14
A Simple Array Example
#include <stdio.h>
int main(void)
{
int i , x[ 5 ] , total = 0 ;
for ( i = 0 ; i < 5 ; i++ )
{
printf( “Enter mark %d” , i );
scanf ( “%d” , &x[ i ] );
}
for ( i = 0 ; i < 5 ; i++ )
total = total + x[ i ];
printf ( “The average is %d” , total / 5 );
return 0;
} 12/6/2020 15
ARRAYS
• DON'T declare arrays with subscripts larger than you will
need; it wastes memory.
• DON'T forget that in C, arrays are referenced starting with
subscript 0, not 1.
12/6/2020 16
Sample program
#include<stdio.h>
main()
{
int a[5],i;
printf(‘enter the array elements”);
for(i = 0;i<5;i++)
scanf(“%d”, &a[i]);
printf(“Array in the reverse order”);
for(i = 5;i>0;i--)
printf(“%d”,a[i]);
} 12/6/2020 17
#inlcude<stdio.h>
#define Max 5;
main();
{
int a[Max], i, min;
int pos = 0;
printf(“Enter the array elements”);
for(i=0;i<5;i++)
scanf(‘%d”,&a[i]);
min = a[0];
for(i=1;i<Max;i++)
if(a[i] < min)
{
min = a[i];
pos = i;
}
printf(“ Minimum Value = %d” , min);
printf(“ Position of the Minimum Value = %d” , pos);
}
12/6/2020 18
Two-Dimensional Arrays
• Two-dimensional Array: a collection of a fixed number of components
arranged in two dimensions
• All components are of the same type
• The syntax for declaring a two-dimensional array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding positive integer
values
12/6/2020 19
Two-Dimensional Arrays (continued)
• The two expressions intexp1 and intexp2 specify the number
of rows and the number of columns, respectively, in the array
• Two-dimensional arrays are sometimes called matrices or
tables
12/6/2020 20
Two Dimensional Array
12/6/2020 21
Two Dimensional Array is defined any Two of axis of XY or YZ or ZX in the graph
X
Y
Z
12/6/2020 22
Two Dimensional Arrays
Syntax data_type array_name[size_1][size_2];
Description Data_type valid data type in C language
Array_name name given to the array
Size_1 is the row size of the array
Size_2 is the column size of the array
Example int a[3][3];
float b[4][4];
Int a[3][2];
12/6/2020 23
Two Dimensional Array Initializing
int table [2][3] = {0,0,0,1,1,1};
int table [2][3] = {{0,0,0},{1,1,1}};
int table [2][3] = {
{0,0,0},
{1,1,1}
};
int table [ ][3] = {
{0,0,0}
{1,1,1}
}; 12/6/2020 24
Two Dimensional Array Initializing
If the values are missing in an initializer, they are automatically set to zero. For instance, the
statement
int table [2][3] = {{1,1}, {2}};
will initialize the first two elements of the first row to one, the first element of the second
row to two , and all other elements to zero.
When all the elements are to be initialized to zero, the following short – cut method may be
used.
int m[3][5] = { {0},{0},{0} };
The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero, The following statement will also achieve the same result:
int m[3][5] = {0,0};
12/6/2020 25
Accessing Array Components
• The syntax to access a component of a two-dimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are expressions yielding nonnegative integer
values
• indexexp1 specifies the row position and indexexp2 specifies the column
position
12/6/2020 26
0 1 2
0
1
2
3
4 25.75
12/6/2020 27
Multi – Dimensional Arrays
12/6/2020 28
X
Y
Z
• Three or More Dimensional Array is called
the Multi – Dimensional Arrays.
• Three Dimensional array defined in any
three of axis of XYZ OR YZX OR ZXY in
the graph
Multi Dimensional Arrays
• This arrays have more than one dimensions.
Syntax data_type array_name[size1][size2]…….[sizen];
Description Data_type valid data type in C language
Array_name name given to the array
Size1,size2 are the sizes of the dimensions
Example Int a[3][3][3];
Float b[4][4][4];
12/6/2020 29
CHARACTER ARRAYS
AND STRINGS
12/6/2020 30
Character and Strings
• An char array is a group of characters that store related data
• A String is a special char array that does not store related data, but a
single piece of data made up of a number of characters OR A string is a
sequence of character that is treated as a single data item. Any group of
characters defined between double quotation marks is a string constant.
• Example: Grades can be stored in a char array with the values A,B,C,D,F;
when we want to print a specific grade we use only 1 element of the array
• Example: But for grades like “Pass” and “Fail” we must print ALL the
elements
12/6/2020 31
String Conti…
• Most Computers languages have a string data type; C does
NOT
• There are 3 ways to store strings in memory
• Fixed Length
• Stored Length
• Terminated
• C adopts the Terminated String approach
• A string in C is an array of chars terminated by the String
Terminator or NULL character 0
12/6/2020 32
Common String Operation
1. Reading and Writing Strings
2. Combining strings together
3. Copying one string to another
4. Comparing strings for equality
5. Extracting a portion of a string
12/6/2020 33
Declaring and Initializing of String
The General form of String is
char string_name [size];
Example:
char city [10];
char name[30];
When the complier assigns a character string to a character array, it automatically
supplies a multicharacter (‘0’) at the end of the string. Therefore, the size should be
equal to the maximum number of characters in the string plus one.
C Permits a character array to be initialized in either of the following two forms:
char city [9] = “ NEW YORK”;
char city [9] = {‘N’.’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’);
C also permits us to initialize a character array without specifying the number of
elements. In such cases, the size of the array will be determined automatically, base on
the number of elements initialiazed. For Example, the statement
char string [ ] = {‘G’,’O’,’O’,’D’,’0’};
12/6/2020 34
Declaring Conti….
We can also declare the size much larger than the string size in the initializer. That is, the
statement.
char str[9] = “GOOD”;
12/6/2020 35
G O O D 0 0 0 0 0
The following declaration is illegal.
(I) char str[5];
str = “GOOD”;
This will result in a compile time error. Also note that we cannot separate the
initialization from declaration.
(II) char s1[4] = “abc”;
char s2[4];
s2 = s2; /* Error */
is not allowed. An array name cannot be used as the left operand of an
assignment operator.
Creating a String in C
12/6/2020 36
h
i
!
array1820
1821
1822
h
i
!
/0
string2820
2821
2822
2823
READING STRINGS FROM TERMINAL
The familiar input function scanf can be used with %s format specification to read in a string of characters.
Example:
char address [10];
scanf(“%s”,address);
The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore, if the
following line of text is typed in at the terminal,
NEW YORK
then only the string “NEW” will be read into the array address, since the blank space after the word ‘NEW’ will
terminate the string reading.
The scanf calls in the case of character arrays, the ampersand (&) is not required before the variable name.
The address array is created in the memory as shown below:
12/6/2020 37
N E W O ? ? ? ? ? ?
Note that the unused locations are filled with garbage.
If we want to read the entire line “NEW YORK”, then we may use two character arrays of approximate
sizes. That is,
char adr1[5], adr2[5];
scanf(“%s %s”,adr1,adr2);
With the line of text
NEW YORK
READING STRINGS FROM TERMINAL
12/6/2020 38
We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters
from the input string.
Example: scanf(“%ws”,name);
Here two things may happen.
1. The width w is equal to or greater than the number of characters typed in. The entire string will be
stored in the string variable.
2. The width w is less than the number of characters in the string. The excess characters will be
truncated and left unread.
Consider the following statements:
char name [10];
scanf(“%5s”,name);
The input string RAM and KRISHNA will be stored as:
R A M 0 ? ? ? ? ? ?
K R I S H 0 ? ? ? ?
Reading a Line of Text
We have seen just now that scanf with %s or %ws can read only strings without white spaces. That is, they
cannot be used for reading a text containing more than one word. However, C Supports a format specification
known as the edit set conversion code % [..] that can be used to read a line containing a variety of characters,
including white spaces. Recall that we have used this conversion code in the program segment
char line [80];
scanf (“%[^n]”,line);
printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen. We would very rarely use this
method.
12/6/2020 39
Using getchar and gets Functions
To read a single character from the terminal, using the function getchar. We can use this function repeatedly to
read successive single characters from the input and place them into a character array. Thus, an entire line of
text can be read and stored in an array. The reading is terminated when the newline character (‘n’) is entered
and the null character is then inserted at the end of the string. The getchar function call takes the form:
char ch;
ch = getchar ( );
Note that the getchar function has no parameters.
12/6/2020 40
#include <stdio.h>
void main()
{
char line[81], character;
int c;
c = 0;
printf("Enter text. Press <Return> at endn");
do
{
character = getchar( );
line[c] = character;
c++;
}
while(character != 'n');
c = c - 1;
line [c] = '0';
printf("n%sn", line);
}
getchar and gets Conti….
Another and more convenient method of reading a string of text containing white spaces is to use
the library function gets available in the <stdio.h> header file. This is a simple function with one
string parameter and called as under.
gets (str);
str is string variable declared properly. It reads characters into str from the keyboard until a new
line character is encountered and then appends a null character to the string. Unlike scanf, it does
not skip white spaces. For example the code segment
char line [80];
gets (line);
printf(“%s”,, line);
reads a line of text from the keyboard and displays it on the screen. The last two statements may
be combined as follows:
printf(“%s”,gets(line));
C does not provide operators that work on strings directly. For instance we cannot assign one
string to another directly. For example, the assignment statements.
string = “ABC”
string1 = string2;
are not valid.
12/6/2020 41
12/6/2020 42
#include<stdio.h>
void main()
{
char string1[80],string2[80];
int i;
printf("Enter a string n");
printf("?");
scanf("%s",string2);
for(i=0;string2[i] != 'o'; i++)
string1[i] = string2[i];
string1[i] = 'o';
printf("n");
printf("%sn", string1);
printf("Number of characters = %dn",i);
}
12/6/2020 43
WRITING A STRINGS TO SCREEN
We have used extensively the printf function with %s format to print strings to the screen. The format %s
can be used to display an array of characters that is terminated by the null character. For example, the statement
printf(“%s”, name);
can be used to display the entire contents of the array name.
We can also specify the precision with which the array is displayed. For instance, the specification
%10.4
Indicates that the first four characters are to be printed in a field width of 10 columns.
However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed left-justified.
Using putchar and puts Functions
Like getchar, C supports another character handling function putchar to output the values of character variables. It
takes the following form:
char ch = ‘A’;
putchar (ch);
The function putchar requires one parameter. This statement is equivalent to:
printf(“%c”,ch);
We have used putchar function to write characters to the screen. We can use this function repeatedly to output a
string of characters stored in an array using a loop:
12/6/2020 44
Example:
char name[6] = “PARIS”;
for(i=0;i<5;i++)
putchar (name[i]);
putchar(‘n’);
Another and more convenient way of printing string values is to use the function
puts declared in the header file <stdio.h>. This is a one parameter function and
invoked as under:
puts (str);
Where str is a string variable containing a string value. This prints the value of the
string variable str and then moves the cursor to the beginning of the next line on
the screen. For example, the program segment
char line [80];
gets (line);
puts (line);
Reads a line of text from the keyboard and displays it on the screen. Note that the
syntax is very simple compared to using the scanf and printf statements
Using putchar and puts Functions Conti…
Function Action
strcat ( ) Concatenates two strings
strcmp ( ) Compares two strings
strcpy ( ) Copies one strings over another
strlen ( ) Finds the length of a string
12/6/2020 45
The C Library supports a large number of string – handling function that can be used to carry out many of the string
manipulations.
The most commonly used string – handling functions.
STRING HANDLING FUNCTIONS

More Related Content

What's hot

C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
Selvaraj Seerangan
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Array in c language
Array in c languageArray in c language
Array in c languagehome
 
Arrays in c
Arrays in cArrays in c
Arrays in c
CHANDAN KUMAR
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++Fahim Adil
 
Array and string
Array and stringArray and string
Array and string
prashant chelani
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
PratikNaik41
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
Online
 
Arrays
ArraysArrays
Array in c programming
Array in c programmingArray in c programming
Array in c programming
Mazharul Islam
 

What's hot (20)

C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Strings in C
Strings in CStrings in C
Strings in C
 
C Pointers
C PointersC Pointers
C Pointers
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Array in c language
Array in c languageArray in c language
Array in c language
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Array and string
Array and stringArray and string
Array and string
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Arrays
ArraysArrays
Arrays
 
Array in c programming
Array in c programmingArray in c programming
Array in c programming
 

Similar to Arrays & Strings

COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
Hemantha Kulathilake
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
nmahi96
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Rakesh Roshan
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Data structure array
Data structure  arrayData structure  array
Data structure array
MajidHamidAli
 
02 arrays
02 arrays02 arrays
02 arrays
Rajan Gautam
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
Arrays
ArraysArrays
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Arrays In C
Arrays In CArrays In C
Arrays In C
yndaravind
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
trupti1976
 
Array
ArrayArray

Similar to Arrays & Strings (20)

COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
2 arrays
2   arrays2   arrays
2 arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
02 arrays
02 arrays02 arrays
02 arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Arrays
ArraysArrays
Arrays
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
 
Array
ArrayArray
Array
 

More from Munazza-Mah-Jabeen

Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
Munazza-Mah-Jabeen
 
The Standard Template Library
The Standard Template LibraryThe Standard Template Library
The Standard Template Library
Munazza-Mah-Jabeen
 
Object-Oriented Software
Object-Oriented SoftwareObject-Oriented Software
Object-Oriented Software
Munazza-Mah-Jabeen
 
Templates and Exceptions
 Templates and Exceptions Templates and Exceptions
Templates and Exceptions
Munazza-Mah-Jabeen
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
Munazza-Mah-Jabeen
 
More About Strings
More About StringsMore About Strings
More About Strings
Munazza-Mah-Jabeen
 
Streams and Files
Streams and FilesStreams and Files
Streams and Files
Munazza-Mah-Jabeen
 
Lists and Tuples
Lists and TuplesLists and Tuples
Lists and Tuples
Munazza-Mah-Jabeen
 
Files and Exceptions
Files and ExceptionsFiles and Exceptions
Files and Exceptions
Munazza-Mah-Jabeen
 
Functions
FunctionsFunctions
Pointers
PointersPointers
Repitition Structure
Repitition StructureRepitition Structure
Repitition Structure
Munazza-Mah-Jabeen
 
Inheritance
InheritanceInheritance
Inheritance
Munazza-Mah-Jabeen
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Munazza-Mah-Jabeen
 
Memory Management
Memory ManagementMemory Management
Memory Management
Munazza-Mah-Jabeen
 
Arrays and Strings
Arrays and StringsArrays and Strings
Arrays and Strings
Munazza-Mah-Jabeen
 
Objects and Classes
Objects and ClassesObjects and Classes
Objects and Classes
Munazza-Mah-Jabeen
 
Functions
FunctionsFunctions
Structures
StructuresStructures
Structures
Munazza-Mah-Jabeen
 
Loops and Decisions
Loops and DecisionsLoops and Decisions
Loops and Decisions
Munazza-Mah-Jabeen
 

More from Munazza-Mah-Jabeen (20)

Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
The Standard Template Library
The Standard Template LibraryThe Standard Template Library
The Standard Template Library
 
Object-Oriented Software
Object-Oriented SoftwareObject-Oriented Software
Object-Oriented Software
 
Templates and Exceptions
 Templates and Exceptions Templates and Exceptions
Templates and Exceptions
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
More About Strings
More About StringsMore About Strings
More About Strings
 
Streams and Files
Streams and FilesStreams and Files
Streams and Files
 
Lists and Tuples
Lists and TuplesLists and Tuples
Lists and Tuples
 
Files and Exceptions
Files and ExceptionsFiles and Exceptions
Files and Exceptions
 
Functions
FunctionsFunctions
Functions
 
Pointers
PointersPointers
Pointers
 
Repitition Structure
Repitition StructureRepitition Structure
Repitition Structure
 
Inheritance
InheritanceInheritance
Inheritance
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Arrays and Strings
Arrays and StringsArrays and Strings
Arrays and Strings
 
Objects and Classes
Objects and ClassesObjects and Classes
Objects and Classes
 
Functions
FunctionsFunctions
Functions
 
Structures
StructuresStructures
Structures
 
Loops and Decisions
Loops and DecisionsLoops and Decisions
Loops and Decisions
 

Recently uploaded

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

Arrays & Strings

  • 2. Definition of Array An array is a fixed – size sequenced collection of elements of the same data type. It is simply a grouping of like – type data. In its simplest form, an array can be used to represent a list of numbers, or list of names. (OR) “A set of consecutive storage location referred by a single name to store homogeneous data type.” int A[10] Array is a Collection of Homogenous Data Items Example 1. List of employees in an organization. 2. List of products and their cost sold by a store. 3. Test Scores of a class of students. 12/6/2020 2
  • 3. 1. One Dimensional Array. 2. Two Dimensional Array. 3. Multi Dimensional Array Types of Array
  • 4. One Dimensional Array 12/6/2020 4 X Y Z One Dimensional Array is defined any one of axis (X or Y or Z) in the graph
  • 5. Arrays So far, we've been declaring simple variables int i; It is also possible to declare an array of Several elements. an array is a variable that can hold more than one value , The declaration int a[10]; declares an array, named a, consisting of ten elements, each of type int. We can represent the array a above with a picture like this: 12/6/2020 5 •Arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9.
  • 6. • An array uses a single identifier, together with an integer index, to create one variable that can hold many values • An array is created the same as a “normal” variable, but with the addition of square brackets indicating the size of the array • Each value in the array is called an element 12/6/2020 6 Arrays
  • 7. One Dimensional Arrays Syntax data_type array_name[size]; Description Data_type valid data type in C language Array_name name given to the array Size are the size of the dimensions Example int a[3]; float b[4]; 12/6/2020 7
  • 8. Initializing Arrays • An array is initialized using a code block containing comma-delimited values which match in position the elements in the array • If there are values in the initialization block, but not enough to fill the array, all the elements in the array without values are initialized to 0 in the case of float or int, and NULL in the case of char • If there are values in the initialization block, an explicit size for the array does not need to be specified, only an empty Array Element Operator is needed. C will count the values and size the array for you. 12/6/2020 8
  • 9. Initializing Arrays int x [ 5 ] = { 1,2,3,4,5 }; size 10 bytes creates array with elements 0-4 values 1-5 int x [ 5 ] = { 4,3 }; size 10 bytes creates array with elements 0-4 values 4,3,0,0,0 int x [ ] = { 1,2,3 }; size 6 bytes creates array with elements 0-2 values 1,2,3 char c [ 4 ] = { ‘M’ , ‘o’ , ‘o’ }; size 4 bytes creates array with elements 0-3 values M o o NULL 12/6/2020 9
  • 10. Arrays •The first element of the array is x[0], the second element is x[1].. e.g x[0] = 10; x[1] = 20; x[2] = 30 x[3] = 40 x[4] = 50 Total = 150; This loop sets all ten elements of the array a to 0. int a[i]; int i; for(i = 0; i < 10; i = i + 1) a[i] = 0; To copy the contents of one array to another, you must again do so one by one: int b[10]; for(i = 0; i < 10; i = i + 1) b[i] = a[i]; Printing Array Values for(i = 0; i < 10; i = i + 1) printf("%dn", a[i]); 12/6/2020 10
  • 11. Array Basics • An array has a fixed number of elements based on its creation • The elements are ALWAYS numbered from 0 to 1 less than the array’s size • Referencing an element outside of the created bounds is possible but not recommended 12/6/2020 11
  • 12. Visual Representation of an Array 12/6/2020 12 Identifier? ? 23 ? int x[4]; x[2]=23; 342901 342903 342905 342917 0 1 2 3 X Address Offset Value
  • 13. The Array Element Operator [ ] • The Array Element Operator is used to reference a specific array element • The expression inside the Array Element must resolve to type int. This value is known as an index • The value of the index can be any number, but care should be taken that the index falls within the bounds of the array. The bounds of an array are defined as 0 to 1 less than the size of the array 12/6/2020 13
  • 14. Array Example #include <stdio.h> int main(void) { int x[5]; x[0]=23; valid x[2.3]=5; invalid: index is not an int x[6]=45; valid but not recommended return 0; } 12/6/2020 14
  • 15. A Simple Array Example #include <stdio.h> int main(void) { int i , x[ 5 ] , total = 0 ; for ( i = 0 ; i < 5 ; i++ ) { printf( “Enter mark %d” , i ); scanf ( “%d” , &x[ i ] ); } for ( i = 0 ; i < 5 ; i++ ) total = total + x[ i ]; printf ( “The average is %d” , total / 5 ); return 0; } 12/6/2020 15
  • 16. ARRAYS • DON'T declare arrays with subscripts larger than you will need; it wastes memory. • DON'T forget that in C, arrays are referenced starting with subscript 0, not 1. 12/6/2020 16
  • 17. Sample program #include<stdio.h> main() { int a[5],i; printf(‘enter the array elements”); for(i = 0;i<5;i++) scanf(“%d”, &a[i]); printf(“Array in the reverse order”); for(i = 5;i>0;i--) printf(“%d”,a[i]); } 12/6/2020 17
  • 18. #inlcude<stdio.h> #define Max 5; main(); { int a[Max], i, min; int pos = 0; printf(“Enter the array elements”); for(i=0;i<5;i++) scanf(‘%d”,&a[i]); min = a[0]; for(i=1;i<Max;i++) if(a[i] < min) { min = a[i]; pos = i; } printf(“ Minimum Value = %d” , min); printf(“ Position of the Minimum Value = %d” , pos); } 12/6/2020 18
  • 19. Two-Dimensional Arrays • Two-dimensional Array: a collection of a fixed number of components arranged in two dimensions • All components are of the same type • The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values 12/6/2020 19
  • 20. Two-Dimensional Arrays (continued) • The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array • Two-dimensional arrays are sometimes called matrices or tables 12/6/2020 20
  • 21. Two Dimensional Array 12/6/2020 21 Two Dimensional Array is defined any Two of axis of XY or YZ or ZX in the graph X Y Z
  • 23. Two Dimensional Arrays Syntax data_type array_name[size_1][size_2]; Description Data_type valid data type in C language Array_name name given to the array Size_1 is the row size of the array Size_2 is the column size of the array Example int a[3][3]; float b[4][4]; Int a[3][2]; 12/6/2020 23
  • 24. Two Dimensional Array Initializing int table [2][3] = {0,0,0,1,1,1}; int table [2][3] = {{0,0,0},{1,1,1}}; int table [2][3] = { {0,0,0}, {1,1,1} }; int table [ ][3] = { {0,0,0} {1,1,1} }; 12/6/2020 24
  • 25. Two Dimensional Array Initializing If the values are missing in an initializer, they are automatically set to zero. For instance, the statement int table [2][3] = {{1,1}, {2}}; will initialize the first two elements of the first row to one, the first element of the second row to two , and all other elements to zero. When all the elements are to be initialized to zero, the following short – cut method may be used. int m[3][5] = { {0},{0},{0} }; The first element of each row is explicitly initialized to zero while other elements are automatically initialized to zero, The following statement will also achieve the same result: int m[3][5] = {0,0}; 12/6/2020 25
  • 26. Accessing Array Components • The syntax to access a component of a two-dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values • indexexp1 specifies the row position and indexexp2 specifies the column position 12/6/2020 26
  • 27. 0 1 2 0 1 2 3 4 25.75 12/6/2020 27
  • 28. Multi – Dimensional Arrays 12/6/2020 28 X Y Z • Three or More Dimensional Array is called the Multi – Dimensional Arrays. • Three Dimensional array defined in any three of axis of XYZ OR YZX OR ZXY in the graph
  • 29. Multi Dimensional Arrays • This arrays have more than one dimensions. Syntax data_type array_name[size1][size2]…….[sizen]; Description Data_type valid data type in C language Array_name name given to the array Size1,size2 are the sizes of the dimensions Example Int a[3][3][3]; Float b[4][4][4]; 12/6/2020 29
  • 31. Character and Strings • An char array is a group of characters that store related data • A String is a special char array that does not store related data, but a single piece of data made up of a number of characters OR A string is a sequence of character that is treated as a single data item. Any group of characters defined between double quotation marks is a string constant. • Example: Grades can be stored in a char array with the values A,B,C,D,F; when we want to print a specific grade we use only 1 element of the array • Example: But for grades like “Pass” and “Fail” we must print ALL the elements 12/6/2020 31
  • 32. String Conti… • Most Computers languages have a string data type; C does NOT • There are 3 ways to store strings in memory • Fixed Length • Stored Length • Terminated • C adopts the Terminated String approach • A string in C is an array of chars terminated by the String Terminator or NULL character 0 12/6/2020 32
  • 33. Common String Operation 1. Reading and Writing Strings 2. Combining strings together 3. Copying one string to another 4. Comparing strings for equality 5. Extracting a portion of a string 12/6/2020 33
  • 34. Declaring and Initializing of String The General form of String is char string_name [size]; Example: char city [10]; char name[30]; When the complier assigns a character string to a character array, it automatically supplies a multicharacter (‘0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one. C Permits a character array to be initialized in either of the following two forms: char city [9] = “ NEW YORK”; char city [9] = {‘N’.’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’); C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, base on the number of elements initialiazed. For Example, the statement char string [ ] = {‘G’,’O’,’O’,’D’,’0’}; 12/6/2020 34
  • 35. Declaring Conti…. We can also declare the size much larger than the string size in the initializer. That is, the statement. char str[9] = “GOOD”; 12/6/2020 35 G O O D 0 0 0 0 0 The following declaration is illegal. (I) char str[5]; str = “GOOD”; This will result in a compile time error. Also note that we cannot separate the initialization from declaration. (II) char s1[4] = “abc”; char s2[4]; s2 = s2; /* Error */ is not allowed. An array name cannot be used as the left operand of an assignment operator.
  • 36. Creating a String in C 12/6/2020 36 h i ! array1820 1821 1822 h i ! /0 string2820 2821 2822 2823
  • 37. READING STRINGS FROM TERMINAL The familiar input function scanf can be used with %s format specification to read in a string of characters. Example: char address [10]; scanf(“%s”,address); The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore, if the following line of text is typed in at the terminal, NEW YORK then only the string “NEW” will be read into the array address, since the blank space after the word ‘NEW’ will terminate the string reading. The scanf calls in the case of character arrays, the ampersand (&) is not required before the variable name. The address array is created in the memory as shown below: 12/6/2020 37 N E W O ? ? ? ? ? ? Note that the unused locations are filled with garbage. If we want to read the entire line “NEW YORK”, then we may use two character arrays of approximate sizes. That is, char adr1[5], adr2[5]; scanf(“%s %s”,adr1,adr2); With the line of text NEW YORK
  • 38. READING STRINGS FROM TERMINAL 12/6/2020 38 We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. Example: scanf(“%ws”,name); Here two things may happen. 1. The width w is equal to or greater than the number of characters typed in. The entire string will be stored in the string variable. 2. The width w is less than the number of characters in the string. The excess characters will be truncated and left unread. Consider the following statements: char name [10]; scanf(“%5s”,name); The input string RAM and KRISHNA will be stored as: R A M 0 ? ? ? ? ? ? K R I S H 0 ? ? ? ?
  • 39. Reading a Line of Text We have seen just now that scanf with %s or %ws can read only strings without white spaces. That is, they cannot be used for reading a text containing more than one word. However, C Supports a format specification known as the edit set conversion code % [..] that can be used to read a line containing a variety of characters, including white spaces. Recall that we have used this conversion code in the program segment char line [80]; scanf (“%[^n]”,line); printf(“%s”,line); will read a line of input from the keyboard and display the same on the screen. We would very rarely use this method. 12/6/2020 39 Using getchar and gets Functions To read a single character from the terminal, using the function getchar. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character (‘n’) is entered and the null character is then inserted at the end of the string. The getchar function call takes the form: char ch; ch = getchar ( ); Note that the getchar function has no parameters.
  • 40. 12/6/2020 40 #include <stdio.h> void main() { char line[81], character; int c; c = 0; printf("Enter text. Press <Return> at endn"); do { character = getchar( ); line[c] = character; c++; } while(character != 'n'); c = c - 1; line [c] = '0'; printf("n%sn", line); }
  • 41. getchar and gets Conti…. Another and more convenient method of reading a string of text containing white spaces is to use the library function gets available in the <stdio.h> header file. This is a simple function with one string parameter and called as under. gets (str); str is string variable declared properly. It reads characters into str from the keyboard until a new line character is encountered and then appends a null character to the string. Unlike scanf, it does not skip white spaces. For example the code segment char line [80]; gets (line); printf(“%s”,, line); reads a line of text from the keyboard and displays it on the screen. The last two statements may be combined as follows: printf(“%s”,gets(line)); C does not provide operators that work on strings directly. For instance we cannot assign one string to another directly. For example, the assignment statements. string = “ABC” string1 = string2; are not valid. 12/6/2020 41
  • 42. 12/6/2020 42 #include<stdio.h> void main() { char string1[80],string2[80]; int i; printf("Enter a string n"); printf("?"); scanf("%s",string2); for(i=0;string2[i] != 'o'; i++) string1[i] = string2[i]; string1[i] = 'o'; printf("n"); printf("%sn", string1); printf("Number of characters = %dn",i); }
  • 43. 12/6/2020 43 WRITING A STRINGS TO SCREEN We have used extensively the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement printf(“%s”, name); can be used to display the entire contents of the array name. We can also specify the precision with which the array is displayed. For instance, the specification %10.4 Indicates that the first four characters are to be printed in a field width of 10 columns. However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed left-justified. Using putchar and puts Functions Like getchar, C supports another character handling function putchar to output the values of character variables. It takes the following form: char ch = ‘A’; putchar (ch); The function putchar requires one parameter. This statement is equivalent to: printf(“%c”,ch); We have used putchar function to write characters to the screen. We can use this function repeatedly to output a string of characters stored in an array using a loop:
  • 44. 12/6/2020 44 Example: char name[6] = “PARIS”; for(i=0;i<5;i++) putchar (name[i]); putchar(‘n’); Another and more convenient way of printing string values is to use the function puts declared in the header file <stdio.h>. This is a one parameter function and invoked as under: puts (str); Where str is a string variable containing a string value. This prints the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. For example, the program segment char line [80]; gets (line); puts (line); Reads a line of text from the keyboard and displays it on the screen. Note that the syntax is very simple compared to using the scanf and printf statements Using putchar and puts Functions Conti…
  • 45. Function Action strcat ( ) Concatenates two strings strcmp ( ) Compares two strings strcpy ( ) Copies one strings over another strlen ( ) Finds the length of a string 12/6/2020 45 The C Library supports a large number of string – handling function that can be used to carry out many of the string manipulations. The most commonly used string – handling functions. STRING HANDLING FUNCTIONS