0% found this document useful (0 votes)
20 views48 pages

Chapter 05

c++

Uploaded by

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

Chapter 05

c++

Uploaded by

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

Chapter Two

Arrays, Strings and Structure

Samilen
1
Array
• is a series of elements of the same type placed
in contiguous memory locations
• referenced by adding an index to a unique
identifier.
• in arrays the First index is always 0
• Example, an array to contain 5 integer values
of type int called billy could be represented

• Where each blank panel represents an element of the array


2
Array Declaration

• An array must be declared before it is used.


• Declaration of an array in C++ is:

Type var_name [index];

• Where type is a valid type (like int, float...),


var_name is a valid identifier and the index field
(which is always enclosed in square brackets []),
• Index field : specifies how many of these
elements the array has to contain.
int billy [5];
3
• Brackets [] which represents the number of
elements the array is going to hold, must be a
constant value
• since arrays are blocks of non-dynamic
memory whose size must be determined
before execution

4
Initializing Arrays
• In both cases, local and global, when we declare
an array, we have the possibility to assign initial
values to each one of its elements by enclosing the
values in braces { }.

int billy [5] = { 16, 2, 77, 40, 12071 };

5
• The amount of values between braces { }
must not be larger than the number of
elements that we declare for the array
between square brackets [ ].
– Value b/n {} !>than elements b/n []
• C++ allows the possibility of leaving the
square brackets empty [ ].
int billy [] = { 16, 2, 77, 40, 12071 };

• After this declaration, array billy would be 5


ints long, since we have provided 5
initialization values.
6
Accessing values of an Array
• we can access the value of any of its elements
individually as if it was a normal variable
• Syntax: var_name [index];
• the name which we can use to refer to each element is
the following:

• Example, to store the value 75 in the third element of


billy, we could write the following statement

billy[2] = 75;
• Example, to pass the value of the third element of billy
to a variable called a, we could write:
a = billy[2];
7
• Notice that the third element of billy is specified
billy[2], since the first one is billy[0], the second
one is billy[1], and therefore, the third one is
billy[2].
• accessing out-of-range elements do not cause
compilation errors but can cause Runtime errors.
• the two uses that bracket [ ] have related to
arrays:
– They perform two different tasks:
• to specify the size of arrays when they are declared;
• to specify indices for concrete array elements

8
Example

int billy[5]; // declaration of a new array


billy[2] = 75; // access to an element of the array.

billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;

9
Example

// arrays example Output


#include <iostream> 12206

int billy [] = {16, 2, 77, 40, 12071};


int n, result=0;
int main (){
for ( n=0 ; n<5 ; n++ ) {
result += billy[n];
}
cout << result;
return 0;
} 10
Array of 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 („\o‟).
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\o’
• To declare an array str that could hold a 10-
characters string, one would write:
– Char str[11];
• Specifying the size as 11 makes room for the null at
the end of the string.

11
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
cin stream.
//the following program reads (part of ) a string entered by
the user: Problem: entering the string
#include <iostream.h> “this is a test “ the above program only
int main() returns “this “ , not the entire
{ sentence.
char str[80];
cout << “Enter a string: “; Reason: the c++ input / output system
cin >> str; // read string from keyboard stops reading when the first
//gets(str);// solution whitespace character is encountered.

cout << “Here is your string: “; Solution: use another c++ library
cout << str; function, gets()
return 0; } 12
Some C++ Library Functions for Strings

• C++ supports a range of string manipulation


functions, the most common are:
– strcpy() : copy characters from one string to another
– strcat() : concatenation of strings
– strlen() : length of a string
– strcmp() : comparison of string

13
Copying of string Length of string
strcpy (to_string, from_string ) strlen (str) returns the length of the string
pointed to by str,
i.e., the number of characters excluding the
#include <iostream.h> null terminator.
int main() #include <iostream.h>
{ int main()
char a[10]; {
strcpy(a, “hello”); char str[80];
cout << a; cout << “Enter a string: “;
return 0; gets(str);
} cout << “Length is: “ << strlen(str);
Return 0; }
14
String concatenation
Strcat(string_1,string_2);
The strcat() function appends s2 to the end of s1. String s2 is
unchanged.

#include<iostream.h>.
int main() output
{ hello there
char s1[21], s2[11]; there
strcpy(s1, “hello”);
strcpy(s2, “ there”);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return 0;}

15
Two Dimensional Arrays
• is a list of one dimensional arrays.
• Syntax:
Type var_name [index] [index];

– Eg. int matrix [3][4];//this corresponds to a table


with 3 rows and 4 columns
#include <iostream.h> matrix[row][col] = (row*4)+ col +1;
int main() cout << matrix*row+*col+ << ‘ ‘;
{ }
int row=3, col=4; cout << ‘\n’;
int matrix[row][col]; return 0;
for(row=0; row < 3; ++row) }
for(col=0; col < 4; ++col) {
16
• jimmy represents a bi-dimensional array of 3 per 5 elements of type int.
• The way to declare this array in C++ would be:

int jimmy [3][5];


• Example, the way to reference the second element vertically and fourth
horizontally in an expression would be:

• Remember that array indices always begin by zero).


17
Multidimensional Arrays

• Can be described as "arrays of arrays".


• are not limited to two indices (i.e., two
dimensions).
• They can contain as many indices as needed.
Example:
– declaration of multi dimensional Arrays in C++ are:
Type var_name [size] [size] [size] [size];
char century [100][365][24][60][60];
• Declares an array with a char element for each second in a century,
which is more than 3 billion chars. So this declaration would consume
more than 3 gigabytes of memory!

18
• Multidimensional arrays are just an abstraction
for programmers, since we can obtain the same
results with a simple array just by putting a
factor between its indices:

1 int jimmy [3][5]; // is equivalent toint


2 jimmy [15]; // (3 * 5 = 15)

• With the only difference that with


multidimensional arrays the compiler remembers
the depth of each imaginary dimension for us.
– One uses a bi dimensional array and the other one
uses a simple array:
19
multidimensional array pseudo-multidimensional array

#define WIDTH 5#
#define WIDTH 5 define HEIGHT 3
#define HEIGHT 3 int jimmy [HEIGHT * WIDTH];
int jimmy [HEIGHT][WIDTH]; int n,m;
int n,m; int main (){
int main (){ for (n=0;n<HEIGHT;n++)
for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++)
for (m=0;m<WIDTH;m++) {
{ jimmy[n][m]=(n+1)*(m+1); jimmy[n*WIDTH+m]=(n+1)*(m+1
} return 0;} );
} return 0;}
20
Structure
Introduction
• C/C++ arrays allow you to define variables that combine
several data items of the same kind, but structure is
another user defined data type which allows you to
combine data items of different kinds.
• Structures are used to represent a record, suppose you
want to keep track of your books in a library. You might
want to track the following attributes about each book
• Title
• Author
• Subject
• Book ID
• Structure is a collection of variables of different data types
under a single name.
Cont..
• For example: You want to store some information about a
person: his/her name, citizenship number and salary. You
can easily create different variables name, citNo, salary to
store these information separately.
• However, in the future, you would want to store
information about multiple persons. Now, you'd need to
create different variables for each information per
person: name1, citNo1, salary1, name2, citNo2, salary2
• You can easily visualize how big and messy the code
would look.
• Also, since no relation between the variables (information)
would exist, it's going to be a daunting task.
Cont..
• A better approach will be to have a collection of
all related information under a single name Person,
and use it for every person.
• Now, the code looks much cleaner, readable and
efficient as well.
• This collection of all related information under a
single name Person is a structure.
How to declare a structure in C++ programming?

• The struct keyword defines a structure type


followed by an identifier (name of the structure).
• Then inside the curly braces, you can declare one
or more members (declare variables inside curly
braces) of that structure. Syntax:-
struct [structure tag] {
member definition;
member definition; ...
member definition;
} [one or more structure variables];
Cont..
• For example:
struct Person {
char name[50];
int age;
float salary;
};
• Here a structure person is defined which has three
members: name, age and salary.
Cont..
• When a structure is created, no memory is
allocated.
• The structure definition is only the blueprint for
the creating of variables. You can imagine it as a
datatype.
• Note: Remember to end the declaration with a
semicolon (;)
How to define a structure variable?

• Once you declare a structure person as above. You


can define a structure variable as:
Person tola; Here, a structure variable tola is defined
which is of type structure Person.
• When structure variable is defined, only then the
required memory is allocated by the compiler.
• Considering you have either 32-bit or 64-bit
system, the memory of float is 4 bytes, memory
of int is 4 bytes and memory of char is 1 byte.
• Hence, 58 bytes of memory is allocated for
structure variable tola.
Structure initialization
struct Person {
char name[50];
int age;
float height;
};
• To initialize a variable of type Person, you can use the following syntax:

Person p = {“Chaltu", 30, 1.75};


This initializes a variable called p of type Person with the values “Chaltu" for the
name, 30 for the age, and 1.75 for the height.

29
How to access members of a structure?

• The members of structure variable is accessed using


a dot (.) operator.
• Suppose, you want to access age of structure
variable bill and assign it 50 to it. You can perform
this task by using following code below:
p.age = 50;
Example: C++ Structure
• C++ Program to assign data to members cout << "Enter salary: ";
of a structure variable and display it. cin >> p1.salary;
#include <iostream> cout << "\nDisplaying Information."
using namespace std; << endl;
struct Person { cout << "Name: " << p1.name <<
char name[50]; endl;
int age; cout <<"Age: " << p1.age << endl;
float salary; cout << "Salary: " << p1.salary;
}; return 0;
int main() { }
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";

cin >> p1.age;


Cont..
• The output of the above code is:
Enter Full name: Gemechu Tola
Enter age: 27
Enter salary: 1024.4
Displaying Information.
Name: Gemechu Tola
Age: 27
Salary: 1024.4
• Here a structure Person is declared which has three
members name, age and salary.
• Inside main() function, a structure variable p1 is defined.
• Then, the user is asked to enter information and data
entered by user is displayed.
Array of structure
• In C++, an array of structures is simply an array in which each element of the
array is an instance of a structure. Here is an example of how to create an array of
structures in C++:
Include<iostream>
Using namespaspace std;
struct Person {
string name;
int age;
};
int main() {
Person people[3]; // create an array of 3 Person structures
// set the values for each element in the array
people[0].name = “Dabala";
people[0].age = 25;
people[1].name = “Meti”;
people[1].age = 30;
people[2].name = “Meri";
people[2].age = 20;
return 0;
}
33
Cont..
• In the example above, we define a Person structure with two fields, name
and age.
• We then create an array of Person structures called people with three
elements.
• We set the values for each element in the array by accessing the fields of
each structure.
• You can access and modify elements of the array of structures using the
same syntax as with any other array
• For example, to print the name and age of the second person in the array,
you can do:

cout << "Name: " << people[1].name << ", Age: " << people[1].age << endl;

34
Nested structure
• nested structure is a structure that is defined inside another
structure. This is also known as a "nested struct" or a "struct
within a struct".
• To define a nested structure in C++, you can simply declare a
structure inside another structure's definition. Here is an
example:
struct outer {
int a;
struct inner {
int b;
int c;
} i;
};

35
Cont..
• In this example, the outer structure contains an integer
a, as well as an inner structure i that has two integer
members, b and c.
• To access the members of the nested structure, you can
use the dot operator twice. For example, to assign a
value to b, you can do:
outer o;
o.i.b = 10;
• In this example, we create an instance of the outer
structure called o, and then we set the value of o.i.b to
10.
• Nested structures are useful when you need to group
related data together, and you want to keep the code
organized and easy to read.
36
Structure pointer
• Structure pointer in C++" refers to the use of
pointers in C++ programming language to access
and manipulate data stored in structures.
• A pointer is a variable that stores the memory
address of another variable.
• It allows us to indirectly access and manipulate the
value stored in a particular memory location.
• In C++, we can declare a pointer to a structure
using the "->" operator, which lets us access the
members of the structure through the pointer.

37
Cont..
• Here's an example of how to declare and use a structure pointer in C++:
#include <iostream>
using namespace std;
// declare a structure
struct Person {
string name;
int age;
};
int main() {
// declare a structure variable
Person p1 = {“Lenjissa", 30};
// declare a pointer to the structure
Person *ptr = &p1;
// access the members of the structure using the pointer
cout << "Name: " << ptr->name << endl;
cout << "Age: " << ptr->age << endl;
return 0;
}

38
Cont..
• In this example, we first declare a structure named
Person that contains two members: name and age.
• Then, we declare a structure variable p1 and
initialize it with the values “Lenjissa" and 30.
• Next, we declare a pointer ptr to the Person
structure and initialize it with the address of p1
using the & operator.
• Finally, we use the -> operator to access the
members of the structure through the pointer and
print their values to the console.

39
Structure to pointer
• we can declare an array of structures to store
multiple instances of the same data type. We can
also use pointers to access and manipulate the data
stored in the array.
• Here's an example of how to convert a structure
array to a pointer in C++:

40
Cont..
#include <iostream>
using namespace std;
// declare a structure
struct Person {
string name;
int age;
};
int main() {
// declare an array of structures
Person people[3] = {{“Jaalu", 30}, {“Meti", 25}, {“Beka", 40}};
// declare a pointer to the first element of the array
Person *ptr = &people[0];
// access the members of the structures using the pointer
for (int i = 0; i < 3; i++) {
cout << "Name: " << (ptr+i)->name << endl;
cout << "Age: " << (ptr+i)->age << endl;
}
return 0;
}
41
Cont..
• In this example, we first declare an array of Person
structures named people with three elements. Each
element contains a name and age member.
• Next, we declare a pointer ptr to the first element of
the people array using the & operator.
• Finally, we use a loop to iterate through each element
of the array and print the values of their members to
the console using the -> operator.
• We use (ptr+i) to access the next element of the array.
Or
• We can also increment the pointer ptr by one in each
iteration to access the next element of the array. Look
the following example

42
Cont..
#include <iostream>
using namespace std;
// declare a structure
struct Person {
string name;
int age;
};
int main() {
// declare an array of structures
Person people[3] = {{"Jalu", 30}, {“Meti", 25}, {“Beka", 40}};
// declare a pointer to the first element of the array
Person *ptr = &people[0];
// access the members of the structures using the pointer
for (int i = 0; i < 3; i++) {
cout << "Name: " << ptr->name << endl;
cout << "Age: " << ptr->age << endl;
ptr++;
}
return 0;
} 43
C++ Structure and Function

• Structure variables can be passed to a function and


returned in a similar way as normal arguments.
• Passing structure to function in C++
• A structure variable can be passed to a function in
similar way as normal argument. Consider example
on the next slide:
Example 1: C++ Structure and Function

#include <iostream> cin >> p.salary; // Function call


using namespace std; with structure variable as an
struct Person { argument
char name[50]; displayData(p);
int age; return 0;
float salary; }; }
void displayData(Person); void displayData(Person p) {
int main() { cout << "\nDisplaying
Information." << endl;
Person p; cout << "Name: " << p.name
cout << "Enter Full name: "; << endl;
cin.get(p.name, 50); cout <<"Age: " << p.age <<
cout << "Enter age: "; endl;
cin >> p.age; cout << "Salary: " << p.salary;
cout << "Enter salary: "; }
Cont..
• Output
Enter Full name: Darartu Bekele
Enter age: 55
Enter salary: 34233.4
Displaying Information.
Name: Darartu Bekele
Age: 55
Salary: 34233.4
• In this program, user is asked to enter the name, age and salary of a
Person inside main() function.
• Then, the structure variable p is to passed to a function using,
displayData(p);
• The return type of displayData() is void and a single argument of
type structure Person is passed.
• Then the members of structure p is displayed from this function.
Example 2: Returning structure from function in C++

#include <iostream> cout << "Enter Full name: ";


using namespace std; cin.get(p.name, 50);
struct Person { cout << "Enter age: ";
char name[50]; cin >> p.age;
int age; cout << "Enter salary: ";
float salary; }; cin >> p.salary;
Person getData(Person); return p;
void displayData(Person); }
int main() { void displayData(Person p) {
Person p, temp; cout << "\nDisplaying
temp = getData(p); Information." << endl;
p = temp; cout << "Name: " << p.name <<
endl;
displayData(p); cout <<"Age: " << p.age <<
return 0; endl; cout << "Salary: " <<
} p.salary;
Person getData(Person p) { }
Cont..
• In this program, we have created
two structure variables p and temp of type Person under
the main() function.
• The structure variable p is passed to getData() function which
takes input from the user which is then stored in
the temp variable.
temp = getData(p);
• We then assign the value of temp to p.
• p = temp;Then the structure variable p is passed
to displayData() function, which displays the information.
• Note: We don't really need to use the temp variable for most
compilers and C++ versions. Instead, we can simply use the
following code:
• p = getData(p);

You might also like