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

c++-5

Uploaded by

Solomon Asfaw
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)
30 views

c++-5

Uploaded by

Solomon Asfaw
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/ 31

BIC COLLEGE

Compiled by:-NANBON TEMASGEN


College :-BIC
Department :-CS
YEAR:II
COURSE:-Fundamentals of c++
Ch-5

Array, pointers and


Strings
Array
 An array is a data structure that allows you to store multiple elements of the same data
type in a contiguous block of memory.
 Arrays provide a convenient way to work with collections of data by allowing you to access
elements using indices.
Use of Array
Arrays are used in programming because they:
 Group Data: Arrays help organize similar data together.
 Sequential and Random Access: Allow for efficient access to elements.
 Memory Efficiency: Contiguous storage reduces memory overhead.
 Simplicity: Provide a straightforward way to store and access data.
 Performance: Good performance for common tasks like indexing and iteration.
 Foundation for Data Structures: Form the basis for more complex data structures.
Arrays simplify data organization, enable efficient access, and form the building blocks for
many programming tasks and data structures.
 Array can be categorized into two part
1)Single dimensional Array
2)Multi dimensional Array
How we declared an Array?
Just like declaration as ordinary variable of different types such as
int roll no, float avg, char name and so on,As we mentioned in the
definition of array , Array is an groups of elements that can be
identifies as a similar types.
Yet there is difference between ordinary variable and array variable
that is you needs to tell the compiler what kind of array is you are
defining, an array of books? An array of students? An arrays of
cloths? because the compiler wants to Know that how much amount
of space will be required to stored an array element or data item in
the computer memory. When declaring the array of elements in the
program, the compiler will put each item of array in
appropriate location Like any other variable.
The syntax of declaration of an array is:
Datatypes variable_name[dimension/size]
o datatypes could be an int, a float , and char etc,
o Variable_name is following according to C++ naming rules ,After the
Variable_name is then, we have to specifies the dimension or size of an
array(i.e the size should be specified with the opening square and closing
square[]).
 Some example of an declaring an Arrays.
o int rollno[20];
o char grade[100] ;
o double marks[20];
 int rollno[10]; declares a group of element or array of 10 values, each
element is being an integer.
 char grade[100]; declares an array of 100 character values.
 double marks[360]; declares an array of double-precision numbers. There
are 360 of these items in the group.
NB:-Array index always start with 0
Initializing an Array:
o We can individually assigned value to an array such as Rollno[0]=1;
rollno[1]=2;…………..upto rolln0[19]=20;
o Just like any variable can be initialized, an array also can be
initialized.
o To accomplish this, for a one-dimensional array, the syntax used is:
 Data Type variable Name[dimension/size] = { element1,
element2, ..,element n};
 the data type specify that what kind of array you are declaring,
then followed by the array name, and the square brackets.
 After specifying the dimension or not, and after the closing square
bracket, type the assignment operator. The elements, also called
items that compose the array are included between an opening
curly brace '{' and a closing curly brace '}'.
Initializing an Array:
 Each element of an array is separate from the other by a comma
operator.
 After the bracing is complete then you end it with a semi-colon.
 Consider an example:
 int rollno[12]={1,2,3,4,5,6,7,8,9,10,11,12};
 double distance[5] = {44.14, 720.52, 96.08, 468.78,
6.28};
 If you have decided to initialize the array while you are declaring
it, you
can omit the dimension.
Therefore, these arrays can be declared as follows:
int rollno[]={1,2,3,4,5,6,7,8,9,10,11,12}
double distance[] = {44.14, 720.52, 96.08, 468.78,
6.28};
Example:
#include <iostream>
include namepace::std;
int main()
{
int rollno[] = {101, 102, 103, 104, 105};
cout << "2nd member = " << rollno[1] <<endl;
cout << "5th member = " << rollno[4] << endl;
return 0;
}
Out put
2nd member = 102
5th member = 105
//second example
#include <iostream>
include namepace::std;
int main()
{
int rollno[] = {101, 102, 103, 104, 105}; out put
cout << " rollno 1: " << ro11no[0] << endl;
cout << " rollno 2: " << rollno[1] << endl;
cout << " rollno 3: " << rollno[2] << endl;
cout << " rollno 4: " << rollno[3] << endl;
cout << " rollno 5: " << rollno[4] << endl;
return 0;
}
The Size of an Array:
 When array has been declared, the programmer has to decides that
how many element should have to initialize depend the size of array.
 The size of array decrease or increases depend upon the requirement of
program.
 Sometimes the programmer doesn’t want to increase or decreases the
size of an array, One method is fixed the size of an array i.e
 constant ,const is reserved keyword or Qualifier , if we declared
the const keyword with an variable assigned with certain value
that value cannot modified or altered during the execution of the
program.
 If the program is long and the array is declared in some unusual place,
this could take some time.
 The alternative is to define a constant keyword before declaring the
array and use that constant to hold the dimension or size of the an
array.
The Size of an Array:
#include<iostream>
//include namespace::std;
int main()
{
const int number_Of_Items=5;
int rollno[number_Of_Items]={101,102,103,104,105};
std::cout<<"rollno 1:"<<rollno[0]<<std::endl;
std::cout<<"rollno 2:"<<rollno[1]<<std::endl;
std::cout<<"rollno 3"<<rollno[2]<<std::endl;
std::cout<<"rollno 4:"<<rollno[3]<<std::endl;
std::cout<<"rollno 5:"<<rollno[4]<<std::endl;
return 0;}

Out put
rollno 1: 101
rollno 2: 102
rollno 3: 103
rollno 4: 104
rollno 5: 105
2-D ARRAYS
 As we have seen the example of one- dimensional array, we also have seen
the how to initialized the data item / elements to one – dimensional array.
 The array that's contain numbers of rows and columns like a the matrix i.e.
the array which contain the two square brackets and mentioned the size of an
arrays is called as a 2-D arrays or 2 dimensional arrays .
Declaration of 2-D arrays:
 Datatypes variablename[dimension/size][dimension/size]
o int anArray[3][5]; // a 3-element array of 5-element arrays or three rows
and 5 columns In this case, since we have 2 subscripts or index , this is
called as a two dimensional array.
o In a two-dimensional array:-
 the first subscript or index consider as an row, and
 the 2nd subscript or index considers as an column.
o the above two-dimensional array is laid out as follows:

o A 2-dimensional array declaration defines as like of matrix of variables or


the same type: int anArray[3][5]
2-D ARRAYS con’t

 Since computer memory is linear, the elements of a 2-dimensional


array are actually stored linear formed int anArray[3][4]

 These variables can be referred to individually with the subscript


operator, e.g., anArray[1][2].
 The set of variables can be referred to as an aggregate with the array
name, e.g., anArray.
 In C++, the first element of an array has the subscript 0.
 In C++, the last element of an array with n element has the subscript
n1.
 In C++, the range of valid index of an m x n array is [0..m-1[[0..n-1].
 Using a index outside of the valid range is an error. This error will not
be detected by the compiler; it will shown as a run time error. In some
cases, it will cause the program to crash; in other cases, the program
will appear to run normally, but will produce incorrect results.
2-D ARRAYS con’t

 The subscript of an array is also called an index.


 A two-dimensional array can called as an array of arrays.
Initialization: Example of initialization 2-d arrays :
2-D ARRAYS con’t

#include <iostream>
int main() {
const int numRows = 3;
const int numCols = 4;
// Initialize a 2D array with 3 rows and 4 columns
int matrix[numRows][numCols] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access and print elements of the 2D array
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) { out put
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
2-D ARRAYS con’t

Explanation:
 Array Declaration - In this example, `matrix` is a two-dimensional array with 3
rows and 4 columns.
Initialization:
- The array is initialized using an initializer list with values for each row and column.
- In the example, the matrix is initialized with values `{1, 2, 3, 4}`, `{5, 6, 7, 8}`, and
`{9, 10, 11, 12}`.
 Accessing Elements:
- Elements in a 2D array are accessed using two indices: one for the row and one for
the column.
- To access an element at row `i` and column `j`, you use `matrix[i][j]`.
 Printing the Array - The nested `for` loops iterate over each element of the 2D
array and print them row by row.
- The outer loop iterates over rows (`i`), and the inner loop iterates over columns
(`j`).
 Output - The program will output the elements of the 2D array in a tabular
format, with each row printed on a new line.
Two-dimensional arrays are useful for representing matrices, tables, grids, and other
structured data where elements are logically organized in rows and columns. They
provide a way to store and manipulate data in a structured manner, making it easier to
2-D ARRAYS con’t example

#include<iostream>
#define nNumRows 5
#define nNumCols 5
int main()
{
int nProduct[nNumRows ][nNumCols ] = { 0};
// Calculate a multiplication table
for (int nRow = 0; nRow < nNumRows; nRow++)
for (int nCol = 0; nCol < nNumCols; nCol++)
nProduct[nRow][nCol] = nRow * nCol;

//Print the table


for (int nRow = 1; nRow < nNumRows; nRow++)
{
for (int nCol = 1; nCol < nNumCols; nCol++)
std::cout<<nProduct[nRow][nCol] << "\t";
std::cout<<std::endl; out put
}
return 0;
}
2-D ARRAYS con’t example

#include<iostream>
#define nNumRows 5
#define nNumCols 5
int main()
{
int nProduct[nNumRows ][nNumCols ] = { 0};
// Calculate a multiplication table
for (int nRow = 0; nRow < nNumRows; nRow++)
for (int nCol = 0; nCol < nNumCols; nCol++)
nProduct[nRow][nCol] = nRow * nCol;

//Print the table


for (int nRow = 1; nRow < nNumRows; nRow++)
{
for (int nCol = 1; nCol < nNumCols; nCol++)
std::cout<<nProduct[nRow][nCol] << "\t";
std::cout<<std::endl; out put
}
return 0;
}
MULTIDIMENSIONAL ARRAYS

 The elements of an array can be of any data type, An array of


arrays is called a multidimensional arrays.
 Multidimensional arrays may be larger than two dimensions.
 Here is a declaration of a three-dimensional array: int
anArray[5][4][3];
INTRODUCTION TO POINTERS

 When you declare the variables in the program the complier


allocated a logical address to the variable in the main memory i.e
When you declare a variable in the progaram, the computer
allocates amount of space for that variable, and uses the
variable's name to refer to that memory space.
 When you declares an a varaibles in the program the space is
created in the memory that assigning the address of the
particular variable that space is used for holding the values of
that particular variable.
 Therefore, everything you declare has an address, just like the
address of your house. You can find out what address a particular
variable is using.
 when you declares a variable, its tell the compiler what kind of
variable is .i.e which data type variable has in the program i.e
whether the variable consist the integer, floating point character
and so on.
INTRODUCTION TO POINTERS
 Pointer is an variable is used to hold the memory address of another variable.
 if you want to see variable's address of a particular variable, you can use the
&(ampersand) operator followed by the name of the variable.
 Let consider an example for accesing the memory address of the variable
numOfStudents.
 As if you decaled the variable like int numOfStudents; you can get the address of
variable numOfStudents and where the variable laocation is loacted by using: cout
<< &numOfStudents;
 Example
//This program would give you the address of the declared variable:
//Author nanbon
//BIC
#include<iostream>
int main()
{
int i;
std::cout<<"the address of variable num is:"<<&i;
std::cout<<"\n\n";
return 0;
}
OUT PUT
the address of variable i is:0x6aff10
 Notes: The address of variable will differ when the program is execute on
Why Use Pointers?

 When you declare an variable the operating system assigned the


particular unique address to the variable in the main memory, as
we compile the program, the compiler assigned the logical
address to the memory, here the content which is stored in the
logical address space is modified through the pointer variable.
INITIALIZING A POINTER
Variable Initialization:
 In C++, it is crucial to initialize variables before use to ensure that
memory space is allocated and values are assigned by the compiler.
Pointer Initialization:
 When working with a pointer variable (`ptr`) in C++, you must inform
the compiler that it will point to the memory address of another variable
(`X`).
 The pointer variable needs to be initialized with a value to point to.
 Pointers in C++ are initialized like regular variables, using the
assignment operator (`=`).

 Two Primary Methods for Pointer Initialization:

1. Using Address-of Operator (`&`):


o Declare a pointer, e.g., `int* Ptr;`, and then initialize it by assigning the
address of another variable.
Example: `int* Ptr = &Variable;`
2. Direct Initialization:
o Pointers can be directly initialized during declaration in C++.
Example: `int* Ptr = &Variable;`
INITIALIZING A POINTER
//This program could also have the pointer initialized as:
#include<iostream> out put
int main(){
int num=430;
int *ptr=&num;
std::cout<< "The value of num is: " << num << "\n";
std::cout<<"The value of pointer variable is: " << *ptr;
std::cout << "\n\n";
return 0;
}
 Another of the program, you can first declare both variables, then
initialize them later on, when you needed.
//after declaration then initialization
#include<iostream>
int main()
{
int num;
int *ptr;
ptr=&num;
num = 430;
std::cout<< " The value of num is: " << num << "\n";
std::cout<<"The value of pointer variable is:= " <<*ptr<< "\n";
std::cout << "\n";
return 0;
}
A POINTER TO A POINTER

 A pointer to a pointer, also known as a double pointer, is a pointer that


stores the memory address of another pointer.
 It is declared by adding an additional asterisk for each level of
indirection. For instance, `int **ptrToPtr;` declares a pointer to a
pointer to an integer.
 Useful in scenarios involving dynamic memory allocation, multi-
dimensional arrays, and complex data structures like trees and graphs.
 Allows for indirect access to memory locations by first referencing a
pointer that, in turn, points to the actual data.
 Commonly used when passing pointers to functions, facilitating
modifications to the original pointer.
A POINTER TO A POINTER
Example :
#include <iostream>
int main() {
int num = 26;
int *ptr;
int **ptrToPtr;
int *pointer; // Corrected to a pointer variable

ptr = &num;
pointer = &num;
ptrToPtr = &pointer;

std::cout << "The value of num is: " << num << "\n";
std::cout << "The value of pointer variable is: " << *ptr << "\n";
std::cout << "The value of pointer to pointer is: " << **ptrToPtr << "\n";

return 0;
}
Out put
String
Introduction to Strings:
 A string is a sequence of characters.
 Earlier versions of C++ lacked built-in types for strings, making string
manipulation a tedious task involving character arrays.
Introduction of the String Class:**
- The ANSI standard introduced a new class called `string` in C++.
- To use the `string` class, the program must include the `<string>`
header file.
- The `string` class in C++ is comprehensive, offering a rich set of
constructors, member functions, and operators.
Commonly Used Constructors:
- Three commonly used constructors of the `string` class:
- string(); :- Creates an empty string.
- string(const char *str); :-Creates a string from a null-terminated
character array.
- string(const string &str); :- Creates a string from another string
object.
Accessing Strings:
- Initialization of strings using user input via `cin` command has
limitations.
- The string length should not exceed the array size as C++ compiler
does not check bounds on character arrays.
- `cin` cannot handle multi-word strings due to space being considered a
String

Handling Multi-Word Strings:


- Strategies to handle multi-word strings:
- Use `gets()` and `puts()` functions instead of `cin` and `cout`.
- Utilize `cin.get()` function to read strings with spaces.

- Common String Handling Functions:


- Essential string handling functions:
- `strlen()`: Determines the length of a string.
- `strcpy()`: Copies one string into another.
- `strcat()`: Appends one string to the end of another.
- `strcmp()`: Compares two strings.
String Length Function (strlen()):
- Counts the number of characters in a string.
- Excludes the null character `\0` when calculating the length.
#include <iostream>
#include <cstring> // Include the header file for string functions
int main() {
char str[] = "Birge International college!"; // Define a character array
// Calculate the length of the string using strlen()
int length = strlen(str);
// Output the original string and its length
std::cout << "String: " << str << std::endl;
std::cout << "Length of the string: " << length << std::endl;
return 0;
String

-String Copy Function (strcpy()):


- Used to copy the contents of one string into another string.
- Syntax: `strcpy(Destination, Source)`.
- Copies characters from the source string to the destination string until encountering
the null terminator `\0`.
- The destination string must be large enough to accommodate the source string.
example
#include <iostream>
#include <cstring>
int main() {
char source[] = "Hello, World!";
char destination[20]; // Ensure destination has enough space
// Copying the content of source to destination using strcpy()
strcpy(destination, source);
// Output the copied string
std::cout << "Copied String: " << destination << std::endl;
return 0;
}
String

- String Concatenation Function (strcat()):


- Concatenates the source string at the end of the destination
string.
- Syntax: `strcat(Destination, Source)`.
- The destination string must have enough space to hold the final
concatenated string.
Example
#include <iostream>
#include <cstring>
int main() {
char destination[20] = "Hello, ";
char source[] = "World!";
// Concatenating source at the end of destination using strcat()
strcat(destination, source);
// Output the concatenated string
std::cout << "Concatenated String: " << destination <<
std::endl;

return 0;
} out put
String

- String Compare Function (strcmp()):


- Compares two strings to determine if they are the same or
different.
- Syntax: `strcmp(String1, String2)`.
- Compares the strings character by character until a mismatch is
found or the end of one string is reached.
- Returns:
- 0 if the strings are equal.
- Numeric difference between the ASCII values of non-matching
characters if they are not equal.
#include <iostream>
#include <cstring>
int main() {
char str1[] = "apple";
char str2[] = "apple";
// Comparing str1 and str2 using strcmp()
int result = strcmp(str1, str2);
if (result == 0) {
std::cout << "Strings are equal" << std::endl;
} else {
std::cout << "Strings are not equal" << std::endl;
}
end

You might also like