[go: up one dir, main page]

0% found this document useful (0 votes)
11 views39 pages

Chapter 4 Arrays & Strings1 , lecture notes

A c++ computer programming course for freshman university students chapter 4 about arrays and strings.

Uploaded by

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

Chapter 4 Arrays & Strings1 , lecture notes

A c++ computer programming course for freshman university students chapter 4 about arrays and strings.

Uploaded by

bamnetesfaye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

CHAPTER 4

Arrays and Strings

1
Objectives
To use the array data structure to represent lists and
tables of values.
To define an array, initialize an array and refer to
individual elements of an array.
 To define symbolic constants.
To use arrays to store, sort and search lists and
tables of values.
 To define and manipulate multidimensional arrays.
 To pass arrays to functions.
 C++ strings
2
Arrays
Literal way Memory case

3
ARRAYS: Are series of elements of the same
type placed in contiguous/ continuous
memory locations that can be individually
referenced by adding an index to a unique
name.

4
Declaration of arrays in C++:
Type array_name [array_size];
ARRAY_SIZE: specifies how many elements the
array has to contain.
int data[5]; // 5 elements all are integers
char ch[10];// 10 elements all are characters
double x[100];// 100 elements all are double

5
Initializing array in c++.
 If an array is declared as global variable it will be
automatically initialized to zero , other wise all the
elements will be garbage values.

 Various types of initializations:


 int data[5]={16,2,77,120,9};
016 1 2 2 77 3 120 4 9
data

 int data[ ]={16,2,77,120,9};// we can leave the size in the


rectangular brace if it is expressed in curly brace.

 int data[5]={16,2,77}// the rest of 2 values are 0.


 int data[5]={0};// all element will be initialized 0. 6
Initialization is not the same as an assignment.
Arrays can be initialized, but they cannot be
assigned:
float a[7] = { 22.2,44.4,66.6 };
float b[7] = { 33.3,55.5,77.7 };
b=a; //ERROR: arrays cannot be assigned!
Nor can an array be used to initialize another
array:
float a[7] = { 22.2,44.4,66.6 };
float b[7] = a; // ERROR: arrays cannot be used
as initializers!
7
Accessing the values of an array.
Elements of array are accessed using index.
Syntax: name[index]
NB: In c++ indexing always starts from 0.
For the above are the name which we can use to
refer to each element is the following:
da[5] ={16,2,77,120,9};
da[0] da[1] da[2] da[3] da[4]
16 2 77 120 9

8
//to store the value 75 in the third element of
data
data[2] = 75; and,
// to assign/pass the value of the third element of
data to a variable called a, we could write:
a=data[2];

9
//A program calculate the sum and average of maximum of 20 numbers entered by the user.
#include<iostream>
using namespace std;
int main()
{
const int max=20;
int data[max];
int count=0,n;
float sum=0,average;
cout<<"how many element do want to enter\? \n";
cin>>n;
if(n<=0||n>20)
cout<<"you entered invalied number\n";
else
{
cout<<"enter your data\n";
for(int i=0;i<n;i++)
{
cout<<"data["<<i<<"]=";
cin>>data[i];
sum+=data[i]; }
average=sum/n;
cout<<"The Sum is ="<<sum<<endl<<"The Average is ="<<average<<endl;
}

return 0;
10
}
Operations on Arrays
Arithmetic operations(+,-,*,/)
looking for a value held by one of array members.
To find minimum and maximum value of a list
To sort some list

11
Searching Array

#include <iostream.h>
int main()
{
int numbers[] = {10, 25, 36, 44, 52, 60, 75, 89};// Declare the
//members of the array
int find, i, m = 8;
cout << "Enter a number to search:";
cin >> find;
for (i = 0; (i < m) && (numbers[i] != find); ++i)
continue;
if (i == m) cout << find << " is not in the list" << endl; // Find whether
the number typed is a member of the array
else
cout << find << " is the " << i + 1<< "th element in the list" << endl;
return 0; 12
Multidimensional Array
=> are arrays of arrays or arrays of two or more
dimension
=>Used to work with data requiring
multidimensional arrays - for example,
matrices and data in the form of a table.

13
Declaration int a[3][5]; // 2D array
Char x[3][5][9] //3D array
Example
• To define a 2D array, two size specifiers are
required: the first one is for the number of
rows and the second one is for the number of
columns.
Eg. float scores[3][4];
• To access a certain element indices or
subscript corresponding to each dimension
should be supplied.
14
• Example

15
16
Each element in a 2D array is accessed with
two subscripts: the first one is for its row and
the second for its column.
Various Initialization options:
int a[2][3]={{1,5,7},{2,3,6}};
int a[2][3]={0};
int a[2][3]={{1,5},{2}}

17
2-D Array Example
#include<iostream>
using namespace std;
int main()
{
const int Numstudents=10;
const int NumHW=3;
double grades[Numstudents][NumHW];
for(int i=0;i<Numstudents;i++)
{
for(int j=0;j<NumHW;j++)
{
cout<<"Enter HW"<<j<<"Grade for Student Number"<<i<<endl;
cin>>grades[i][j];
}
}
return 0;
} 18
Example: write a program that add two matrices, input by the user
#include<iostream>
using namespace std;
const int max_row=50;
const int max_col=50;
int main()
{ int col,row,i,j;
int a[max_row][max_col]={0}, b[max_row][max_col]={0}, c[max_row][max_col]={0};
cout<<"enter the number row and column \n";
cin>>row>>col;
cout<<"enter the element of first matrix \n";
for( i=0;i<row;i++)
for( j=0;j<col;j++)
cin>>a[i][j];
cout<<"enter the element of second matrix \n";
for( i=0;i<row;i++)
for( j=0;j<col;j++)
cin>>b[i][j];
cout<<"a+b=\n"; // c= a+b
for( i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j] = a[i][j] +b[i][j];
for( i=0;i<row;i++)
{ for( j=0;j<col;j++)
cout<<c[i][j]<<"\t";
cout<<endl; 19
Passing Array as an Argument to Function
Passing elements of Array as an argument(one dimensional)
• An indexed variable can be an argument to a function in
exactly the same way that any variable of the array base
type can be an argument
double i, n, a[10];

20
Passing The Entire Array as an argument
(one dimensional)

Passing The Entire Array as an argument


(Two dimensional)

21
22
23
24
25
26
char name[20];
N.B 1.we need not initialize all the available space (20)
2.the string will terminate by the null character ‘\0’
 Initialization
char my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
or char my_string[]=”Hello”
once initialized we can not use the following:
my_string[]=”hello”;
my_string=”Hello”;
my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
 but we can say
my_string [0]=’H’;
my_string[3]=’k’;
cout<< my_string[2];
cout<<my_string; 27
With cin space will not be read.
Hence use the following
cin.getline(char buffer[], int )

Address to store input Max length

28
Eg. // cin with strings
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char mystr[100];
cout<<"What's your name? ";
cin.getline(mystr,100);
cout<<"Hello "<<mystr<< ".\n";
cout<<"What is your favorite team? ";
cin.getline(mystr,100);
cout<<"I like "<<mystr<<" too!\n";
return 0;
}
29
String Manipulations:

Functions to manipulate strings:


Requires string header file in standard c++ and string.h in pre-standard c++.

i)strlen (char buffer[] ) =>returns the length without the null character ‘\0’;
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
char name[50];
cout<<"Enter Your Name:"" ";
cin>>name;
cout<<"The length of Your Name is“<<" "<<strlen(name)<<endl;
return 0;
} 30
String concatenation
ii)strcat(str1, str2) =>to concatenate or merge two strings
NB. 1.The first string str1 hold the concatenated string
2.the size of the first string must be large enough to hold both
strings.
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
char str1[13]="Hello ";
char str2[]="World!";
cout<<"Before: "<<str1<<endl;
cout<<strcat(str1, str2)<<endl;
cout<<"After: "<<str2<<endl;
return 0;
} 31
String compare
iii)strcmp(str1,str2) => for lexical/alphabetical
comparison rule:
• 0 if the two strings are equal
• negative if the first string comes before
the second in alphabetical order
• positive if the first string comes after
the second in alphabetical order

32
String copy

iv) strcpy(str1,str2): is used to copy one string to


another. This is because arrays can't be copied using
the assignment operator (=).
Example:
char str1[20];
char str2[] = "Second String";
strcpy(str1, str2);
cout<<"str1: "<<str1<<endl;
strcpy(str2, "Another String");
cout<<"str2: "<<str2<<endl;
33
String/Numeric Conversion
i)atoi= string to int i)itoa  int to string

ii)atof=string to float ii)ftoi float to string

iii)atoll=string to long iii)ltoa long to string

34
Eg.
int num = atoi("4123"); //num = 4123
long lnum = atol ("12345678");
float fnum = atof ("2.34");
itoa (not standard): converts an integer to a
string. It accepts three arguments
argument1 - the integer to be converted
argument2 - the string to hold the converted
result
argument3 - the base (8, 10, or 16)
char strnum[4];
35
36
37
Example Using at
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string n = "Kebede";
cout<<n.at(0)<<endl;
cout<<n.size()<<endl;
cout<<n.at(n.size()-1)<<endl;
return 0;
} 38
Thank U all!!!

39

You might also like