SlideShare a Scribd company logo
Arrays and Strings
• An array is a collection of variables of the same type
that are referred to by a common name.
• Arrays offer a convenient means of grouping
together several related variables, in one dimension
or more dimensions:
• product part numbers:
int part_numbers[] = {123, 326, 178, 1209};
• student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4,
4};
• characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’,
’E’};
•names:
char names[][40] =
{“Peter”, “Mary”, “Lisa”,
“John”, "George-Simon"};
•3D coordinates:
vector coordinates[4][3] =
Back
{{0, 0, 0},
{1, 0, 1},
{1, 0, 5}
{4, 7, 9}};
One-Dimensional Arrays
A one-dimensional array is a list of related variables
The general form of a one-dimensional array
declaration is:
type variable_name[size]
• type
:
• size:
• variable_name:
base type of the array,
determines the data type of
each element in the array
how many elements the
array will hold the name
of the array
Examples:
int sample[10];
float float_numbers[100];
char last_name[40];
Accessing Array Elements
An individual element within an array is
accessed by use of an index. An index
describes the position of an element
within an array.
Note:
In C++ the first element has the index zero!
Representation of Arrays in Memory
In C++, any array is mapped to a
contiguous memory location. All memory
elements reside next to each other.
The lowest address corresponds to the first
element, and the highest address to the last
element.
Example:
int a[8];
int j;
for(j=0; j<8; j++) a[j] = 7-j;
Then the memory representation of array a looks like
this:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]
7 6 5 4 3 2 1 0
Example: Finding the Maximum
#include <iostream.h> int
main()
{
int i, max = 0; int
list[100];
// initialize the array with
random values
for(i=0; i<100; i++) list[i] = rand();
// findmaximum value
for(i=0; i<100; i++)
if(max < list[i]) max = list[i];
cout << “Maximum value: “ << max;
return(0);
}
No Array-to-Array Assignments
You cannot assign one array to another in
C++. The following is illegal:
int a[10], b[10];
// do something
// assign all elements of array b to array a
a = b; // error -- illegal
Instead, you have to do the assignments for each element:
int i;
// assign all elements of array b to array a
for(i=0; i<10; i++) a[i] = b[i];
Strings
The most common use for one-dimensional arrays is to store
strings of characters.
In C++, a string is defined as a character array terminated by
a null symbol ( ‘0’ ).
To declare an array str that could hold a 10-character string,
one would write:
char str[11];
Specifying the size as 11 makes room for the null at the end of
the string.
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
Some examples of string constants in C++ are:
"hello there"
"I like C++."
"#$%§@@+*"
""" """"
""
""
The null string, ““, only contains the null
terminator and represents the empty string.
Reading a String from the Keyboard
How to read a string entered from the keyboard?
Make an array, that will receive the string, the target of a cin stream. The
following program reads (part of) a string entered by the user:
#include <stdio.h> int
main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
Cout << str;
return(0);}
Problem: Entering the string “This is a test”, the above program
only returns “This”, not the entire sentence.
Reason: The C++ input/output system stops reading a string
when the first whitespace character is encountered.
Solution: Use another C++ library function, gets().
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: “;
gets(str); // read a string from the keyboard
cout << “Here is your string: “;
cout << str << endl;
return(0);}
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions. The
most common are:
• strcpy() :
• strcat() :
• strlen() :
• strcmp() :
copy characters from one string to
another concatenation of strings
length of a string
comparison of
strings
strcpy(to_string, from_string) — String Copy:
#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
h e l l o 0 ? ? ? ?
strlen(string) — String Length
strlen(str) returns the length of the string pointed to by str,
i.e., the number of characters excluding the null terminator.
#include <iostream.h>
#include <cstdio.h>
#include <cstring.h>
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str);
cout << “Length is: “ << strlen(str);
return(0);}
strcat(string_1, string_2) — Concatenation of Strings
The strcat() function appends s2to the end of s1. String s2is
unchanged.
// includes ... int
main()
{
char s1[21], s2[11];
strcpy(s1, “hello”);
strcpy(s2, “ there”);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return(0);
}
Note:
• The first string array has to be large enough to hold both
strings:
• To be on the safe side:
strlen(s1concats2) >= strlen(s1) + strlen(s2)
‘ ‘ t h e r e 0 ? ? ? ?
h e l l o 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9 1011121314151617181920
s1:
0 1 2 3 4 5 6 7 8 9 10
s2:
h e l l o ‘ ‘ t h e r e 0 ? ? ? ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9 1011121314151617181920
strcat(s1,s2):
strcmp(string_1, string_2) — Comparison of Strings
The strcmp(str_1, str_2) function compares two strings
and returns the following result:
• str_1 == str_2
• str_1 > str_2
• str_1 < str_2
: 0
: positive number
: negative
number
The strings are compared lexicographically
(i.e., according to dictionary order):
a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd <
...
// Comparing strings
#include <iostream.h>
#include <cstring.h>
#include <cstdio.h>
int main()
{
char str[80];
cout << “Enter password: “;
gets(str);
if(strcmp(str, “password”)) {
// strings differ
cout << “Invalid password.n”;}
else cout << “Logged on.n”;
return(0);
}
Using the Null Terminator
Operations on strings can be simplified using the fact that all
strings are null-terminated.
// Convert a string to uppercase
// ... includes ...
int main()
{
charstr[80];
int i;
strcpy(str, “this is a test”);
for(i=0; str[i]; i++)
str[i] = toupper(str[i]);
cout << str; return(0); }
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
To declare a two-dimensional integer array two_dim of size
10,20 we would write:
int matrix[3][4];
This corresponds to a table with 3 rows and 4 columns (for
example).
1 2 3 4
5 6 7 8
9 10 11 12
0 1 2 3
0
1
2
Left
Index
Right
Index
two_dim[1][2]
We can generate the array above by using this program:
#include <iostream.h>
int main()
{
int row=3, col=4;
int matrix[row][col];
for(row=0; row < 3; ++row) {
for(col=0; col < 4; ++col) {
matrix[row][col] = (row*4)+ col +1;
cout << matrix[row][col] << ‘ ‘;
}
cout << ‘n’;
}
return(0);}
Memory Allocation for Two-Dimensional Arrays
Storage for all array elements is determined at compile time.
The memory used to hold an array is required the entire time
that the array is in existence.
The following formula determines the number of bytes of
memory that will be allocated:
bytes = rows * columns * number_of_bytes_in_type
For example, an integer array (with two-byte integers) with
dimensions 100,100 would require 100 * 100 * 2 = 20,000
bytes.
Multidimensional Arrays
C++ allows arrays with more than two dimensions.
The general form of an N-dimensional array declaration is:
type array_name [size_1] [size_2] … [size_N];
For example, the following declaration creates a 4 x 10 x 20
character array, or a matrix of strings:
char string_matrix[4][10][20];
This requires 4 * 10 * 20 = 800 bytes.
If we scale the matrix by 10, i.e. to a 40 x 100 x 20 array, then
80,000 bytes are needed.
Array Initialization
The general form of array initialization is similar to that of
other variables:
type array-name[size] = { list-of-values };
The list-of-values has to be a comma-separated list of
constants that are type-compatible with the base type of
the array.
In the following example, a 10-element float array is
initialized with the numbers 1.0 through 10.0:
float i[10] =
{1.,2.,3.,4.,5.,6,7,8,9,10};
Therefore, i[0] will have the value 1.0, and i[9] will
have the value 10.0.
Character Array Initialization
Character arrays that will hold strings allow a shorthand
initialization that takes this form:
char array-name[size] = “string”;
For example, the following code fragment initializes str to
the phrase “hello”:
char str[6] = “hello”;
This is the same as writing
char str[6] =
{‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
Remember that one has to make sure to make the array long
enough to include the null terminator.
Multi-Dimensional Array Initialization
Multi-dimensional arrays are initialized the same way as one-
dimensional arrays.
For example, the following code fragment initializes an array
squares with the numbers 1 through 10 and their squares:
intsquares[9][2] =
{ 1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64,
9, 81 };
For better readability, especially for multi-dimensional arrays,
one can use subaggregate grouping by adding braces
accordingly.
The same declaration as above can also be written as:
int squares[10][2] =
{ {1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
The following program uses the squares array to find the root
of a number entered by the user.
#include <iostream.h>
// declaration of squares array goes here
int main()
{
int i, j;
cout << “Enter a number 1<=i<=100: “;
cin >> i;
// look up i
for(j=0; j<10; j++)
if(squares[j][1] == i) {
cout << "Root: " << squares[j][0];
return(0);}
cout << "No integer root."; return(0);}
© Christian Jacob
Unsized Array Initializations
It is possible to let C++automatically dimension the arrays
through the use of unsized arrays.
char error_1[] = “Divide by 0n”;
char error_2[] = “End-of-Filen”;
char error_3[] = “Access Deniedn”;
C++ will automatically create arrays large enough to hold all
the initializers present.
For a multi-dimensional array, all but the leftmost dimension
have to be specified. So we can write:
char errors[][20] = {
“Divide by 0n”,
“End-of-Filen”,
“Access Deniedn” };
Arrays of Strings
An array of strings is a special form of a two-dimensional array.
• The size of the left index determines the number of strings.
• The size of the right index specifies the maximum length of
each string.
For example, the following declares an array of 30 strings,
each having a maximum length of 80 characters (with one
extra character for the null terminator):
char string_array[30][81];
For accessing an individual string, one simply specifies only
the left index:
firstString = string_array[0];
sixthString = string_array[5];
The following example calls the gets() function with the third
string in the array:
gets(string_array[2]);
This program accepts lines of text entered at the keyboard
and redisplays them after a blank line is entered.
// includes go here
int main()
{
int t, i;
char text[100][80];
// quit on blank line
for(t=0; t<100; t++) {
cout << t << “: “;
gets(text[t]);
if(!text[t][0]) break;
}
for(i=0; i<t; i++) // redisplay the strings
cout << text[i] << ‘n’;
return(0);}
An Example Using String Arrays
Arrays of strings are commonly used for handling
tables of information.
One such application would be an employee database that
stores
• the name
• telephone number
• hours worked per pay period, and
• hourly wage.
These data we could store in arrays:
charname[20][80]; // employee names
int phone[20]; // phone numbers
float hours[20];
loat wage[20];
// hours worked
// wage
Entering Information
void enter()
{
inti;
for(i=0; i<20; i++)
{
cout<< “Lastname: “;
cin>>name[i];
cout<< “Phonenumber: “;
cin>>phone[i];
cout<< “Hoursworked: “;
cin>>hours[i];
cout<< “Wage:“;
cin>>wage[i];
}
}
Displaying Database Contents
Void report()
{
inti;
for(i=0; i <20;i++)
{
cout<< "Name:"<<name[i]<<"/"<<"phone:"
<<phone[i] << ‘n’;
cout<< “Pay for theweek: “;
cout<< wage[i]*hours[i];
cout<<‘n’;
}
}
Menu For User´s Selection
intmenu()
{
intchoice;
cout<< “0.Quitn”;
cout<< “1.Enter informationn”;
cout<< “2.Reportinformationn”;
cout<< “n”;
cout<< “Choose one: “;
cin>> choice;
Return choice;
}
Main Function
int main()
{
int choice;
do {
choice = menu(); // get selection
switch(choice) {
case 0: break;
case 1: enter(); break;
case 2: report(); break;
default: cout << “Try again.nn”;
}
} while( choice != 0);
return(0);
}
© Christian Jacob
Putting It All Together
#include <iostream.h>
// array declarations int
menu();
void enter();
void report();
int main()
{ ... }
int menu()
{ ... }
void enter()
{ ... }
void report() { ... }
Ad

More Related Content

Similar to Arrays & Strings.pptx (20)

17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Chapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdfChapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdf
mylinhbangus
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
kirthika jeyenth
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
Ain-ul-Moiz Khawaja
 
02 arrays
02 arrays02 arrays
02 arrays
Rajan Gautam
 
Strings
StringsStrings
Strings
Imad Ali
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
ARRAYS
ARRAYSARRAYS
ARRAYS
muniryaseen
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Structured data type
Structured data typeStructured data type
Structured data type
Omkar Majukar
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
Education Front
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CGC string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
 
17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
Chapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdfChapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdf
mylinhbangus
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
Structured data type
Structured data typeStructured data type
Structured data type
Omkar Majukar
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CGC string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
 

Recently uploaded (20)

211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Ad

Arrays & Strings.pptx

  • 2. • An array is a collection of variables of the same type that are referred to by a common name. • Arrays offer a convenient means of grouping together several related variables, in one dimension or more dimensions: • product part numbers: int part_numbers[] = {123, 326, 178, 1209}; • student scores: int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4}; • characters: char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};
  • 3. •names: char names[][40] = {“Peter”, “Mary”, “Lisa”, “John”, "George-Simon"}; •3D coordinates: vector coordinates[4][3] = Back {{0, 0, 0}, {1, 0, 1}, {1, 0, 5} {4, 7, 9}};
  • 4. One-Dimensional Arrays A one-dimensional array is a list of related variables The general form of a one-dimensional array declaration is: type variable_name[size] • type : • size: • variable_name: base type of the array, determines the data type of each element in the array how many elements the array will hold the name of the array Examples: int sample[10]; float float_numbers[100]; char last_name[40];
  • 5. Accessing Array Elements An individual element within an array is accessed by use of an index. An index describes the position of an element within an array. Note: In C++ the first element has the index zero!
  • 6. Representation of Arrays in Memory In C++, any array is mapped to a contiguous memory location. All memory elements reside next to each other. The lowest address corresponds to the first element, and the highest address to the last element.
  • 7. Example: int a[8]; int j; for(j=0; j<8; j++) a[j] = 7-j; Then the memory representation of array a looks like this: a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] 7 6 5 4 3 2 1 0
  • 8. Example: Finding the Maximum #include <iostream.h> int main() { int i, max = 0; int list[100]; // initialize the array with random values for(i=0; i<100; i++) list[i] = rand(); // findmaximum value for(i=0; i<100; i++) if(max < list[i]) max = list[i]; cout << “Maximum value: “ << max; return(0); }
  • 9. No Array-to-Array Assignments You cannot assign one array to another in C++. The following is illegal: int a[10], b[10]; // do something // assign all elements of array b to array a a = b; // error -- illegal Instead, you have to do the assignments for each element: int i; // assign all elements of array b to array a for(i=0; i<10; i++) a[i] = b[i];
  • 10. Strings The most common use for one-dimensional arrays is to store strings of characters. In C++, a string is defined as a character array terminated by a null symbol ( ‘0’ ). To declare an array str that could hold a 10-character string, one would write: char str[11]; Specifying the size as 11 makes room for the null at the end of the string. ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
  • 11. Some examples of string constants in C++ are: "hello there" "I like C++." "#$%§@@+*" """ """" "" "" The null string, ““, only contains the null terminator and represents the empty string.
  • 12. Reading a String from the Keyboard How to read a string entered from the keyboard? Make an array, that will receive the string, the target of a cin stream. The following program reads (part of) a string entered by the user: #include <stdio.h> int main() { char str[80]; cout << “Enter a string: “; cin >> str; // read string from keyboard cout << “Here is your string: “; Cout << str; return(0);}
  • 13. Problem: Entering the string “This is a test”, the above program only returns “This”, not the entire sentence. Reason: The C++ input/output system stops reading a string when the first whitespace character is encountered. Solution: Use another C++ library function, gets(). #include <iostream.h> #include <cstdio.h> int main() { char str[80]; // long enough for user input? cout << “Enter a string: “; gets(str); // read a string from the keyboard cout << “Here is your string: “; cout << str << endl; return(0);}
  • 14. Some C++ Library Functions for Strings C++ supports a range of string-manipulation functions. The most common are: • strcpy() : • strcat() : • strlen() : • strcmp() : copy characters from one string to another concatenation of strings length of a string comparison of strings
  • 15. strcpy(to_string, from_string) — String Copy: #include <iostream.h> #include <cstring.h> int main() { char a[10]; strcpy(a, “hello”); cout << a; return(0); } a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] h e l l o 0 ? ? ? ?
  • 16. strlen(string) — String Length strlen(str) returns the length of the string pointed to by str, i.e., the number of characters excluding the null terminator. #include <iostream.h> #include <cstdio.h> #include <cstring.h> int main() { char str[80]; cout << “Enter a string: “; gets(str); cout << “Length is: “ << strlen(str); return(0);}
  • 17. strcat(string_1, string_2) — Concatenation of Strings The strcat() function appends s2to the end of s1. String s2is unchanged. // includes ... int main() { char s1[21], s2[11]; strcpy(s1, “hello”); strcpy(s2, “ there”); strcat(s1, s2); cout << s1 << endl; cout << s2 << endl; return(0); }
  • 18. Note: • The first string array has to be large enough to hold both strings: • To be on the safe side: strlen(s1concats2) >= strlen(s1) + strlen(s2) ‘ ‘ t h e r e 0 ? ? ? ? h e l l o 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 0 1 2 3 4 5 6 7 8 9 1011121314151617181920 s1: 0 1 2 3 4 5 6 7 8 9 10 s2: h e l l o ‘ ‘ t h e r e 0 ? ? ? ? ? ? ? ? ? 0 1 2 3 4 5 6 7 8 9 1011121314151617181920 strcat(s1,s2):
  • 19. strcmp(string_1, string_2) — Comparison of Strings The strcmp(str_1, str_2) function compares two strings and returns the following result: • str_1 == str_2 • str_1 > str_2 • str_1 < str_2 : 0 : positive number : negative number The strings are compared lexicographically (i.e., according to dictionary order): a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd < ...
  • 20. // Comparing strings #include <iostream.h> #include <cstring.h> #include <cstdio.h> int main() { char str[80]; cout << “Enter password: “; gets(str); if(strcmp(str, “password”)) { // strings differ cout << “Invalid password.n”;} else cout << “Logged on.n”; return(0); }
  • 21. Using the Null Terminator Operations on strings can be simplified using the fact that all strings are null-terminated. // Convert a string to uppercase // ... includes ... int main() { charstr[80]; int i; strcpy(str, “this is a test”); for(i=0; str[i]; i++) str[i] = toupper(str[i]); cout << str; return(0); }
  • 22. Two-Dimensional Arrays A two-dimensional array is a list of one-dimensional arrays. To declare a two-dimensional integer array two_dim of size 10,20 we would write: int matrix[3][4]; This corresponds to a table with 3 rows and 4 columns (for example). 1 2 3 4 5 6 7 8 9 10 11 12 0 1 2 3 0 1 2 Left Index Right Index two_dim[1][2]
  • 23. We can generate the array above by using this program: #include <iostream.h> int main() { int row=3, col=4; int matrix[row][col]; for(row=0; row < 3; ++row) { for(col=0; col < 4; ++col) { matrix[row][col] = (row*4)+ col +1; cout << matrix[row][col] << ‘ ‘; } cout << ‘n’; } return(0);}
  • 24. Memory Allocation for Two-Dimensional Arrays Storage for all array elements is determined at compile time. The memory used to hold an array is required the entire time that the array is in existence. The following formula determines the number of bytes of memory that will be allocated: bytes = rows * columns * number_of_bytes_in_type For example, an integer array (with two-byte integers) with dimensions 100,100 would require 100 * 100 * 2 = 20,000 bytes.
  • 25. Multidimensional Arrays C++ allows arrays with more than two dimensions. The general form of an N-dimensional array declaration is: type array_name [size_1] [size_2] … [size_N]; For example, the following declaration creates a 4 x 10 x 20 character array, or a matrix of strings: char string_matrix[4][10][20]; This requires 4 * 10 * 20 = 800 bytes. If we scale the matrix by 10, i.e. to a 40 x 100 x 20 array, then 80,000 bytes are needed.
  • 26. Array Initialization The general form of array initialization is similar to that of other variables: type array-name[size] = { list-of-values }; The list-of-values has to be a comma-separated list of constants that are type-compatible with the base type of the array. In the following example, a 10-element float array is initialized with the numbers 1.0 through 10.0: float i[10] = {1.,2.,3.,4.,5.,6,7,8,9,10}; Therefore, i[0] will have the value 1.0, and i[9] will have the value 10.0.
  • 27. Character Array Initialization Character arrays that will hold strings allow a shorthand initialization that takes this form: char array-name[size] = “string”; For example, the following code fragment initializes str to the phrase “hello”: char str[6] = “hello”; This is the same as writing char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}; Remember that one has to make sure to make the array long enough to include the null terminator.
  • 28. Multi-Dimensional Array Initialization Multi-dimensional arrays are initialized the same way as one- dimensional arrays. For example, the following code fragment initializes an array squares with the numbers 1 through 10 and their squares: intsquares[9][2] = { 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81 };
  • 29. For better readability, especially for multi-dimensional arrays, one can use subaggregate grouping by adding braces accordingly. The same declaration as above can also be written as: int squares[10][2] = { {1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49}, {8, 64}, {9, 81}, {10, 100} };
  • 30. The following program uses the squares array to find the root of a number entered by the user. #include <iostream.h> // declaration of squares array goes here int main() { int i, j; cout << “Enter a number 1<=i<=100: “; cin >> i; // look up i for(j=0; j<10; j++) if(squares[j][1] == i) { cout << "Root: " << squares[j][0]; return(0);} cout << "No integer root."; return(0);}
  • 31. © Christian Jacob Unsized Array Initializations It is possible to let C++automatically dimension the arrays through the use of unsized arrays. char error_1[] = “Divide by 0n”; char error_2[] = “End-of-Filen”; char error_3[] = “Access Deniedn”; C++ will automatically create arrays large enough to hold all the initializers present. For a multi-dimensional array, all but the leftmost dimension have to be specified. So we can write: char errors[][20] = { “Divide by 0n”, “End-of-Filen”, “Access Deniedn” };
  • 32. Arrays of Strings An array of strings is a special form of a two-dimensional array. • The size of the left index determines the number of strings. • The size of the right index specifies the maximum length of each string. For example, the following declares an array of 30 strings, each having a maximum length of 80 characters (with one extra character for the null terminator): char string_array[30][81];
  • 33. For accessing an individual string, one simply specifies only the left index: firstString = string_array[0]; sixthString = string_array[5]; The following example calls the gets() function with the third string in the array: gets(string_array[2]);
  • 34. This program accepts lines of text entered at the keyboard and redisplays them after a blank line is entered. // includes go here int main() { int t, i; char text[100][80]; // quit on blank line for(t=0; t<100; t++) { cout << t << “: “; gets(text[t]); if(!text[t][0]) break; } for(i=0; i<t; i++) // redisplay the strings cout << text[i] << ‘n’; return(0);}
  • 35. An Example Using String Arrays Arrays of strings are commonly used for handling tables of information. One such application would be an employee database that stores • the name • telephone number • hours worked per pay period, and • hourly wage. These data we could store in arrays: charname[20][80]; // employee names int phone[20]; // phone numbers float hours[20]; loat wage[20]; // hours worked // wage
  • 36. Entering Information void enter() { inti; for(i=0; i<20; i++) { cout<< “Lastname: “; cin>>name[i]; cout<< “Phonenumber: “; cin>>phone[i]; cout<< “Hoursworked: “; cin>>hours[i]; cout<< “Wage:“; cin>>wage[i]; } }
  • 37. Displaying Database Contents Void report() { inti; for(i=0; i <20;i++) { cout<< "Name:"<<name[i]<<"/"<<"phone:" <<phone[i] << ‘n’; cout<< “Pay for theweek: “; cout<< wage[i]*hours[i]; cout<<‘n’; } }
  • 38. Menu For User´s Selection intmenu() { intchoice; cout<< “0.Quitn”; cout<< “1.Enter informationn”; cout<< “2.Reportinformationn”; cout<< “n”; cout<< “Choose one: “; cin>> choice; Return choice; }
  • 39. Main Function int main() { int choice; do { choice = menu(); // get selection switch(choice) { case 0: break; case 1: enter(); break; case 2: report(); break; default: cout << “Try again.nn”; } } while( choice != 0); return(0); }
  • 40. © Christian Jacob Putting It All Together #include <iostream.h> // array declarations int menu(); void enter(); void report(); int main() { ... } int menu() { ... } void enter() { ... } void report() { ... }