0% found this document useful (0 votes)
7 views

chapter 2

This document covers Chapter Two of a programming course, focusing on arrays and structures in C++. It explains data types, the differences between homogeneous and heterogeneous data types, and provides detailed information on declaring, accessing, and manipulating arrays and structures. Additionally, it discusses string manipulation techniques using both C-style arrays and the string class in C++.

Uploaded by

bilisumat03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

chapter 2

This document covers Chapter Two of a programming course, focusing on arrays and structures in C++. It explains data types, the differences between homogeneous and heterogeneous data types, and provides detailed information on declaring, accessing, and manipulating arrays and structures. Additionally, it discusses string manipulation techniques using both C-style arrays and the string class in C++.

Uploaded by

bilisumat03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Bule Hora University

Collage of Informatics
Second year software engineering students
Course name: Fundamentals of Programming II
Course code :SEng2021
Chapter Two
Arrays and Structure

BY:Degaga .A
Topics we will cover in this chapter are:

 Data types.
 Homogeneous and heterogeneous data types
 Declaring, accessing and accessing arrays
 Declaring, accessing and accessing structure.
 Difference b/n Arrays and Structure data types
 String manipulation using arrays.

BY:Degaga .A
Data Types
 It defines the kind of data a variable can hold and the operations that can be
performed on that data.
 It determines how much space is needed to store the data and what kind of values
it can take.
 C++ supports several types of data types, which can be broadly categorized into built-in

(primitive) types, user-defined types, and derived types .


 built-in (primitive):These data type are fundamental data type.
• Integer
• Character
• Boolean
• Floating

 Derived Data Types


These are types that are derived from primitive types.
• Arrays
• Pointers
• References
user-defined data types
user-defined data types are data types that programmers create to represent complex
data structures. These types go beyond the built-in types to provide more customized
and organized ways to store data. Here are the main user-defined data types in C++:

• Structures

• Unions (only one member hold memory space at time)


• Enumerations and more
Homogeneous and Heterogeneous data types
 Homogeneous data types refer to collections where all elements are of the same
type. In other words, each item in the collection is of a uniform type. Examples
Arrays and vectors.
 Heterogeneous data types refer to collections where elements can be of different
types. Examples structures,unions,classes and etc.
Arrays
An arrays is a data structure which allows a collective name to be given
to a group of elements which all have the same type(Homogeneous ).
 An individual element of an array is identified by its own unique
index (or subscript).
 The first element in an array in C++ always has the index 0, and if
the array has n elements the last element will have the index n-1.
 An array can be thought of as a collection of numbered boxes each
containing one data item.
 To access a particular item the index of the box associated with the
item is used to access the appropriate box. The index must bean
integer and indicates the position of the element in the array.
 Thus the elements of an array are ordered by the index.
Arrays
 They can be categorized based on their dimensions. Here are the main types of
arrays:
• One dimensional array.
• Two dimensional array.
• Multi dimensional array.

One dimensional array.

 It is the simplest form of an array and is used to store a linear collection of data.
 Example:int numbers[5] = {1, 2, 3, 4, 5};
Declaration of one dimensional array

Declaration of Arrays:
• An array declaration is very similar to a variable declaration.
• First a type is given for the elements of the array, then an identifier
for the array and,within square brackets, the number of elements in
the array.
• The numberof elements must be an integer.
• general format of array declaration is :
data_type (array name) [ size];
in this case size is an integer which shows number of the elements.
example: int temp[5];
Initializing one dimensional array

 array initialization means assign initial values to the array.


when array is intialized,list of elements are enclosed in curly
brackets.
 general format :
data-type identifier or array name [size]={};
example:
Valid array initialization: Invalid array initialization
int array [3]={1,2,3}; int array[2]={1,2,3}
int array []={1,2,3};
int arr[4]={4,6};
Accessing of one dimensional array

 An array element is accessed by writing the identifier of the array


followed by the subscript(index) in square brackets.
 The first element in an array in C++ always has the index 0,
and if the array has n elements the last element will have the
index n-1.
 general format:
 array- name[index];
example:Array[0];
Two dimensional array
 A two-dimensional array is essentially an array of arrays, often used to represent
matrices or grids. It has rows and columns.
Example:

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}}; it indicates 3 rows and 4 column array.
Declaring of two dimensional array

 A two-dimensional array is declared by specifying the number of ro


and columns.
 General format how declare two dimensional array is:
data_type array_name[rows][columns];
 example if you want to declare array of integer with 3 rows and th
columns, we declare like this: int temp [3][3];.also we can declar
different array types as the following: float temp [3][3]; for floa
array, char letters[3][3]; for char array and
std::string students [3][3]; for string.
Initialization of two dimensional array

The general format for initializing a two-dimensional array is described as the


following. The syntax involves enclosing each row of the array in curly braces {}, and
separating the rows by commas. Here’s a breakdown of the general format:
data_type array_name[rows][columns] = {
{value_00, value_01, ..., value_0n}, // Row 0
{value_10, value_11, ..., value_1n}, // Row 1 ...
{value_m0, value_m1, ..., value_mn} // Row m };
Valid two dimensional array initialization:
Example: int list [3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
char letter [3][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'} };
std::string student [2][2] = { {"Hello", "World“,”array”}, {"C++",
"Programming“,”java”} };
Invalid 2d array initialization:
Int number[][]={{1,2},{3,4}};
Accessing of two dimensional array

 In C++, accessing elements of a two-dimensional array is done using two indices:


one for the row and one for the column.
 The general format is: array_name[row_index][column_index];
 Example: temp[0][0], to access elemnt on 0 row and 0 row.
Structure.

 Structure is user defined data type which allows you to


combine data items of different kinds (Heterogeneous ).
 structure is a type in which each value is a collection of
component items.
 the entire collection has a single name.
 each component can be accessed individually.
 Using C++ ‘struct’ keyword
structure definition

 Before creating a structure variable you must create a

structure definition

Syntax for structure definition

struct structname
tag
{ datatype1 variable1;
Membe
datatype2 variable2; rs

};

 Each member has a name and a type

o Names follow the rules for variable names.

o Types can be any defined type.


Cont..

Example :
struct student
{
int id;
char name[15];
};

 You can’t initialize members in struct definition


E.g.
struct date{

int day = 24, month = 10, year = 2001;


}; //this is wrong
Defining and Declaring structure
o Once you have defined a structure you can create a variable
from it
o There are different technique how to Defining and
Declaring structure. Those methods are:
Method 1:
struct student
{
int id; structure definition
char name[15];
student
}; std1; //// structure variable
declaration
Method 2:
Struct
{ //no tag
char id_num[5]; structure definition
char name[10];
char gender;
int age;
}
studno_1, studno_2 ; //structure variable declaration
Cont..

Method 3:
struct student
{
char id_num[5];
char name[10]; structure definition

char gender;
int age;
}
studno_1, studno_2; // structure variable
:method 4
struct student
{
char id_num[5];
char name[10]; structure definition
char gender;
int age;
};

struct student studno_1, studno_2; // structure


variable declaration
Initializing a structure
Structures can be initialized at the time of declaration using a brace-
enclosed list of values. The values in the list are assigned to the
structure's members in the order they are declared.
Syntax:
c
struct StructName {
dataType member1;
dataType member2;
// ...
};

StructName varName = {value1, value2, ...}; //when you create


structure variable
or
varName.member1=value; // once we create structure variable
VarName.member2=value;
Initializing a structure

struct student
{
int id;
char name[15];
};
student std1={“Gizachew", 2337};
 you can assign fewer values than member
variables
 If you try to assign more values than member
variables, you will get a compiler error
#include <iostream>

using namespace std;


struct student
{
int a;
char x; structure definition
char y[20];
};

int main()
{

// intializaing out of scope.

student std1={123,'a',"hello"}; //structure intialization.

cout<<std1.a;
cout<<std1.x; accessing structure.
cout<<std1.y;

return 0;
}
struct student{
int id;
string name;
char gender;
int age;
} studno_1, studno_2;
int main()
{
studno_1.id=123;
studno_1.age= 9;
studno_1.gender='m'; another way of struct intial
studno_1.name="bona";
struct employee
{
int idd;
string name;
char grade;
};

struct employee emp;


int main()
{
emp.idd=134;
emp.grade='a'; structure intialization.

emp.name="saamuhel";
}
Struct
{ //no tag
int year;
char grade;
string id;
}studno_1, studno_2;

int main()
{

studno_1.id="stud/123";
studno_1.grade='a'; structure intialization.
studno_1.year=2022;
Return 0;
}
Accessing Members
 You can treat the members of a struct just like variables.
 To access members of structure we use the name of the record( stru
variable), the name of the member and dot between record and
General syntax for accessing members of structure:
members.
Structure_variable.member_varia
ble;
struct{ //no tag
int year;
char grade;
string id;

}studno_1, studno_2;
accessing the values of member
studno_1.id
int main()
{ studno_1.grade
studno_1.id="stud/123"; studno_1.yea
studno_1.grade='a'; intialization
studno_1.year=2022;
Difference b/n Arrays and Structure data types
array Structure
Type of Data Stored Arrays store multiple elements of the same data type Structures store multiple elements that
can be of different data types

Memory Allocation: Arrays allocate memory in a contiguous block, and Structures allocate memory for each
each element of the array is placed one after the other member individually. The memory
in memory. The size of an array is fixed once declared. layout of the members can vary.
Structure is not allocated in
contiguous.

Accessing Elements Array elements are accessed using an index (zero- Structure members are accessed using
based) the dot operator (.)

Size The size of an array is fixed when it is declared. It The size of a structure depends on the
cannot be resized dynamically unless you use dynamic number and type of members.
memory allocation.
String manipulation
 In many programming languages, strings are represented as an array of
characters, and by treating them as such, you can manipulate strings
element by element (i.e., character by character).
 String manipulation using arrays refers to the process of performing operations
on strings. The task of string manipulation can be achieved using loop and c++
build in function
 String manipulation in C++ can be performed using both C-style Character Arrays
and the more modern string class.
 Each approach has its own set of functions and methods for handling strings,
allowing for a variety of operations: those operation are:
 Accessing individual characters.
 Modifying or replacing characters.
 Reversing the string.
 Concatenating strings.
 Finding substrings.
 Copying strings.
 Changing the case of characters and more

 In C++, string manipulation using arrays can be achieved by either manipulating using

string class and C-style array character .


String manipulation using string class:
 The string class is more versatile and easier to use compared to C-style character arrays.
 Strings are objects that represents sequences of characters.
 To use string type in C++ code first we have to include <string>

 Some string manipulation technique using string class are:


1.Concatenation
Concatenation of Strings is Using the + operator or the append() function to concatenate two
strings.
 string str1 = "Hello, ";
 string str2 = "World!";
 string result = str1 + str2 or str1.append(str2);
2.Inserting a Substring
You can insert a string at a specific position in another string using the insert()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString = "Hello, World!";
// Inserting a substring at position 7
myString.insert(7, "Beautiful ");
cout << "String after insertion: " << myString << endl; return 0;}
3.Accessing Characters
o You can access individual characters using an index:

#include <iostream>
using namespace std;
int main()
{
string str = "Hello";
char c = str[1]; // 'e‘
Cout<<c;
Return 0;
}
3.Reversing a String
You can reverse a string using the reverse() function from the
<algorithm> library.
#include <iostream>
#include <string>
#include <algorithm>
int main()
string hello = "Hello, World!";
reverse(hello.begin(), hello.end());
cout << "Reversed string: " << hello << endl;
return 0;}
4.String Length
To get the length of a string, use the length() or size()
function
#include <iostream>
#include <string>
using namespace
int main()
{ string hello = "Hello, World!";
cout << "Length of the string: " << hello.length() <<
endl;
return 0;}
5.Extracting a substring
 A substring of a string can be extracted(copied) and assigned to another.
 stringName.substr(int copy_start_position, int number_of_elements);

//sample code
#include<iostream.h>
using namespace std;
int main()
{
string s1="Gizachew";
S2=ac
string s2=s1.substr(3,2);
cout<<s2;
}
6.Erasing a substring
 A substring can be deleted from a string.
 stringName.erase(int erase_start_position, int number_of_elements);
//sample code
#include<iostream.h>
using namespace std;
int main(){
string s1="Gizachew"; Gizhew

s1.erase(3,2);
cout<<s1;
7.Replacing a substring
 A substring can be deleted and replaced by another substring.
 stringName.replace(int replace_start_position, int number_of_elements, string s);
//sample code
#include<iostream.h>
using namespace std;
int main(){
Gizachew
string s1="Gizxyhew";
s1.replace(3,2,”ac”);
cout<<s1;
}
String manipulation using C-style Character Arrays:
 C-style strings are essentially arrays of characters terminated by a null character ('\0').

 It declared like this char str[] = “string";

 Example char str[]=“hello” which equivalent to char str[]={ ‘h’,’e’,’l’,’l’,’o’,’\0’ } ,in this case the

length of character is 6.

Some string manipulation using C-style array character are:

1.Converting Case (Uppercase/Lowercase)

myString[i] = myString[i] - 32; //convert to uppercase using loop


or toupper() by including #include <cctype> . //To uppercase using function
myString[i] = myString[i] + 32 //convert to lowercase using loop
tolower() to lowercase //using function
•.
Uppercase and lowercase Conversion loop
#include <iostream>
using namespace std;
int main()
{
char myString[] = “hello, world!"; //C-Style array character.
for (int i = 0; myString[i] != '\0'; i++) //loop through all string till null terminator.
{
if (myString[i] >= 'a' && myString[i] <= 'z') //check all are lowercase and include a between z
//note if the given string not lowercase the program terminate
from the if condition
{
myString[i] = myString[i] - 32; // Convert to uppercase }
}}
cout<<myString;// to display uppercase

mystring=“HELLO,WORLD”; // mystring is intialized by capital letter.


for (int i = 0; myString[i] != '\0'; i++)
{
if (myString[i] >= 'A' && myString[i] <= 'Z')
{
myString[i] = myString[i] + 32;//to lowercase
}}
cout<<myString
return 0; }
Uppercase and lowercase Conversion <ctype.h> library

Using toupper() and tolower() functionwe can automatically handle the conversion.
#include <stdio.h>
#include <ctype.h> // For toupper() and tolower()
int main()
{ char myString[] = "Hello, World!"; //C-style array character.
for (int i = 0; myString[i] != '\0'; i++)
{
myString[i] = toupper(myString[i]);

}
for (int i = 0; myString[i] != '\0'; i++) {
myString[i] = tolower(myString[i]);
}
.Counting Vowels and Consonants using loop

char myString[] = "Hello, World!";

int vowels counter = 0, consonants counrter = 0;

for (int i = 0; myString[i] != '\0'; i++)


{
char ch = tolower(myString[i]); // include this header to lower: #include <cctype>
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
vowels counter ++; }
else if ((ch >= 'a' && ch <= 'z')) // check by their ASCII VALUE
{
consonants counter ++;
}
}
cout << " vowels counter : " << vowels << endl; cout << " consonants counter : " <<
consonants << endl; return 0;
3.Modifying the String
We can modify individual characters in the array by accessing them
using their index.
#include <iostream>
using namespace
int main()
{
char myString[] = "Hello, World!"; in this case H at index=0 and W at index 7
myString[0] = ‘y'; H to y
myString[7] = 'C'; // Changing 'W' to 'C'
cout << "Modified string: " << myString << endl;
return 0;

}
4.String Length using loop
we can calculate the length of the string manually by iterating over the
character array until you reach the null terminator ('\0').
#include <iostream>
using namespace std;
int main()
{
char myString[] = "Hello, World!";
int length = 0; // Calculate length manually
while (myString[length] != '\0') // in this case null terminator not
counted.
So it returns 13.
{
length++; }
5.Finding Frequency of a Character
You can find the frequency of a particular character in a string.
#include <iostream>
using namespace std;
int main() {
char myString[] = "Hello, World!"; //char array
char target = 'l'; int count = 0; //target to find frequency of l.
for (int i = 0; myString[i] != '\0'; i++)
{ if (myString[i] == target) { count++; }
}
cout << "Frequency of '" << target << "' in the string: " << count
<< endl; return 0;}
Reading assignment
1.dynamic array
2.other string manipulation technique.
 Tokenizing a String
 Reversing a String using c-style character using loop
 Counting vowel and consonant without using loop
 Searching a substring using string class.
 Uppercase and lowercase using string class
 Calculate String Length for c-style array without using loop
Thank you
?

You might also like