0% found this document useful (0 votes)
18 views56 pages

Understanding Arrays and Strings in C++

This document provides an overview of arrays and strings in computer programming, specifically focusing on their definitions, types, and usage in C++. It explains one-dimensional and multi-dimensional arrays, including their declaration, initialization, and element access, as well as common string manipulation functions in C++. Additionally, it includes exercises for practical understanding and examples of C++ code for array and string operations.

Uploaded by

tashegirma888
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)
18 views56 pages

Understanding Arrays and Strings in C++

This document provides an overview of arrays and strings in computer programming, specifically focusing on their definitions, types, and usage in C++. It explains one-dimensional and multi-dimensional arrays, including their declaration, initialization, and element access, as well as common string manipulation functions in C++. Additionally, it includes exercises for practical understanding and examples of C++ code for array and string operations.

Uploaded by

tashegirma888
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

Computer Programming

Chapter-4
Array and String

1
OUTLINE

 Definitions of Arrays
 Introduction to one dimensional Array
 Multidimensional Array

2
Definition:
 An array is a data structure containing a number of data
values (all of which are the same data type).
 For Example: an array is a data structure which you can
visualize as follows:
a 5 12 7 9 11 15

b ‘a’ ‘r’ ‘r’ ‘a’ ‘y’ ‘s’

X c ‘a’ ‘r’ ‘r’ ‘a’ ‘y’ ‘s’ 9 11 15

3
Introduction to Arrays
 An array is used to process a collection of data
of the same type
 Examples: - A list of names

- A list of temperatures
 Why do we need arrays?
 Imagine keeping track of 5 test scores, or 100, or
1000 in memory
 How would you name all the variables?
 How would you process each of the variables?
4
Cont…
 The elements of an array are related by the fact that
they have the same array name and type.

 The number used to refer to a particular element of an


array is called its index or subscript.

 The index must be an integer and indicates


the position of the element in the array.

 Thus the elements of an array are ordered by


the index
5
Types of Array
 Based on dimension, there are two types of
Array
Quiz Mid Ass ProJ Final
 One Dimensional Array11 12
21 22
 Multi Dimensional Array
31 32

6
One Dimensional Array
Declaration of arrays
 A typical declaration for an array in C++ syntax is:
type arrayName[size];
 Example, to declare an array numbers as shown
above:
int numbers
[5];
Data type Name of Number of array
of the array the array elements
7
Cont…
 The array size used to declare an array must be a constant expression in
standard C++.
 For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
 But it is all right if SIZE is a constant as follows:
const int SIZE = 4;
double myList[SIZE]; // Correct
 If arrays have the same element type, they can be declared together that
are separated by commas.
 For example,
double listA[10], listB[25];
8
Array Initialization
We can assign values to members of an array at the point of
declaration using the following syntax:
type arrayName[arraySize] = {value0, value1, ..., valuek};
 For example, int numbers[5] = {11, 3, 5, 7, 9};
 This is called the array initializer, declares and initializes the
array numbers with 5 elements in a single statement, making
it equivalent to the statements shown below:
int numbers[5];
numbers[0] = 11;
numbers[1] = 3;
numbers[2] = 5;
numbers[3] = 7;
numbers[4] = 9;

9
Cont…
 int billy [5];

 When we declare an Array, we have the


possibility to assign initial values to each
one of its elements.
int billy [5] = { 16, 2, 77, 40, 12071 };
This looks like:

10
Cont…
 Using an array initializer, Splitting the declaration and initialization parts
would cause a syntax error.
 Thus, the next statement is wrong:

double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
 C++ allows you to omit the array size when declaring and creating an array
using an initializer.
 For example, the following declaration is fine because the compiler
automatically figures out how many elements are in the array:
double myList[] = {1.9, 2.9, 3.4, 3.5};
11
Cont…
 No Array-to-Array Assignments
You cannot assign one array to another in C++.
The following is wrong:
int a[10], b[10];
// Now, 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;
// Now, assign all elements of
// array b to array a
for(i=0; i<10; i++) a[i] = b[i];
12
Accessing Array Elements
 An array element is accessed by writing the name of the array followed by the
subscript 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
 So to access each elements in the array int numbers[5];

numbers[0]; ------- to access the first element.

numbers[1]; ------- to access the second element.

numbers[2]; ------- to access the third element.

numbers[3]; ------- to access the fourth element.

numbers[4]; ------- to access the fifth element


13
 We can use loop to manipulate/process an array.
Cont…
Exercise 1
If an array has five elements, what is the
highest index of a valid element in the
array?

Answer: 4

14
Cont…
Exercise 2
Write the code required to declare an array of
10 Integers called intArray. Then initialize
the array so that each element contains the
value of its index. Hint: Use a loop.
Answer:
int intArray[10];
int index;
for (index = 0 ;index<= 9;index ++)
{
intArray[Index] = Index;
}
15
Cont…
Exercise 3
Write a C++ program that find the sum of the
following numbers by using Array and there by
calculates their average, it should display the
sum and average on two lines.
{4, 3, 5, 2, 1}

16
Cont…
 Exercise 4
Write a C++ program that accepts three numbers by using One
Dimensional Array and then displays the accepted numbers to
the screen.

17
Bidimensional Arrays
 An array may have more than one dimension. Each dimension is represented
as a subscript in the array.

 The simplest form of the multidimensional array is the two-dimensional array.


 A two-dimensional array can be think as a table, which will have x number of
rows and y number of columns.
 A 2-dimensional array a, which contains three rows and four columns can be
shown as below −

18
Cont…
syntax is:
type arrayName[rowSize][columnSize];
 For example, declaring an array numbers as
shown above:
 int
The data Thenumbers
name 3 is [3][2];
the row and 2 is
type of the of the the column of the
array array array

This declaration will cause the compiler to allocate space for (3*2 = 6)
consecutive int variables in memory.
The number of elements in an array must be fixed at compile time.

19
Initializing Two – Dimensional
Arrays
 There are two ways in which a Two-Dimensional array can be
initialized.

First Method:
 int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
 The above array have 3 rows and 4 columns.
 The elements will be filled in the array in the order, first 4 elements from
the left in first row, next 4 elements in second row and so on.

Better Method:
 int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
20
Accessing Elements of Two-Dimensional
Arrays
 Elements in Two-Dimensional arrays are accessed using the row indexes and
column indexes.
 Example:
 int x[2][1];
 The above example represents the element present in third row and second
column.
 To output all the elements of a Two-Dimensional array we can use nested for
loops.
 We will require two for loops. One to traverse the rows and another to
traverse columns.
21
Example -2D array

22
Cont…
// C++ Program to print the elements of a Two-Dimensional array
#include<iostream>
using namespace std;
int main()
{ Output:
// an array with 3 rows and 2 columns. Element at x[0][0]:
int x[3][2] = {{0,1}, {2,3}, {4,5}}; 0 Element at x[0]
// output each array element's value [1]: 1 Element at
for (int i = 0; i < 3; i++)
{
x[1][0]: 2 Element
for (int j = 0; j < 2; j++) at x[1][1]: 3
{ Element at x[2][0]:
4 jElement
cout << "Element at x[" << i << "][" << << "]: "; at x[2]
cout << x[i][j]<<endl; [1]: 5
}}
return 0;
}
23
 Write a C++ program to read a two dimensional
square matrix A and display elements of the matrix
to the screen.

24
25
String Definition
 C++ strings are sequences of characters stored in a char

array.
 Strings of characters allow to represent sequences of characters, like: words,
sentences, texts, etc.

 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’).

 For example, to declare an array str that could hold a 5-character string as
shown above:
char str[6];
 The size is 6 making room for the null at the end of the string.
26
Cont…
 A string variable s1 could be declared as follows:
char s1[10];
 The string variable s1 could hold strings of length up to nine characters

since space is needed for the final null character.


 Strings can be initialized at the time of declaration just as other variables

are initialized. For example:

char s1[] = "example";

In this case the array would be allocated space for eight characters, that is

space for the seven characters of the string and the null character
27
Con….

char s2[20] = “another example”


 Here the string is set by the declaration to be twenty characters long but

only sixteen of these characters are set, i.e. the fifteen characters of the

string and the null character.

28
Cont…
 Some examples of string constants in
C++ are:

The null string, "", only contains the null terminator and represents
the empty string.

29
Cont…
Reading a String 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);
}
30
Cont…
 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);
}

31
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 strings
 First of all, include <cstring.h> or include
<string> in the very first lines of the code.
32
Cont…
 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);
}

33
34
Cont…
#include <iostream.h>
#include <cstring.h>
int main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
system("PAUSE");
return 0;
}

35
Cont…
 There is also another function strncpy, is like
strcpy, except that it copies only a specified number
of characters.
strncpy(destination, source, int n);
#include <iostream.h>
#include <cstring.h>
int main() {
char dest[6] = "Hello";
char src[] = "Hi there!";
strncpy(dest, src, 6);
cout<<src<<endl<<dest;
return 0;
36
}
Cont…
 strlen(string) — String Length :

#include <iostream.h>
strlen(str) returns the length of
#include <cstdio.h>
#include <cstring.h>
the string pointed to by str, i.e.,
int main() the number of characters
{ excluding the null
char str[80]; terminator.
cout << “Enter a string: “;
gets(str); // let the input is: hello
// Length is: 5
cout << “Length is: “ << strlen(str);
return(0);
}
37
Cont…
 strcat(string_1, string_2) — Concatenation of Strings :

#include <iostream.h> The strcat(s1,s2)


#include <cstdio.h> function appends s2 to the
#include <cstring.h> end of s1. String s2 is
int main(){ unchanged.
char s1[21], s2[11];
strcpy(s1, “Hello”); Displays:
strcpy(s2, “ there”);
strcat(s1, s2); Hello there
cout << s1 << endl; there
cout << s2 << endl;
return(0);
}
38
Cont…
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl; output
char str2[] = "xyz"; abc
strcat(str1, str2); abcdef
cout << str1 << endl; abcdefxyz
str1[4] = '\0'; abcd
cout << str1 << endl;

39
Cont…
 The function strncat is like strcat except that it copies only a specified number of
characters.
Strncat(destination, source, int n);
#include <iostream.h> output
#include <cstring.h>
int main() { abc
char str1[30];
strcpy(str1, "abc"); abcde
cout << str1 << endl;
strncat(str1, "def", 2); abcdexyz
str1[5] = '\0';
cout << str1 << endl; abcd
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
system("PAUSE");
return 0;
40
Cont…
 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 :0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
The strings are compared lexicographically
(i.e., according to dictionary order), for example:
a < aa < aaa < … < b < ba < bb < … < bz < baa < … <
abca < abd
41
Cont…
#include <iostream.h>
#include <cstring.h>
int main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
system("PAUSE");
return 0;
}
42
Cont…
 The function strncmp is like strcmp except that it
compares only a specified number of characters.
 strncmp(str1, str2, int n);

int main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
system("PAUSE");
return 0;
}
43
Pointers
Address in C++
 To understand pointers, you should first know how data
is stored on the computer.
 Each variable is assigned a location in the
computer's memory.
 The value the variable stores is actually stored in the
location assigned.
 To know where the data is stored, C++ has an
ampersand ‘&’ symbol.
 The & reference operator gives you the address
occupied by a variable.
 If var is a variable then, &var gives the address of
that variable.
45 Computer Programming 10/29/2025
Example 1: Address in C++
#include <iostream> Output:
using namespace std; 0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4
int main()
{ Note: You may not get the same
int var1 = 3; result on your system.
int var2 = 24;
int var3 = 17; The 0x in the beginning represents
the address is in hexadecimal form.
cout << &var1 << endl;
Notice that first address differs from
cout << &var2 << endl;
second by 4-bytes and second
cout << &var3 << endl;
address differs from third by 4-bytes.

return 0; This is because the size of integer


} (variable of type int) is 4 bytes in 64-
bit system.

46 Computer Programming 10/29/2025


Pointer Definition
 Pointers are used in C++ program to access the
memory and manipulate the address.
 For type T, T* is the type “pointer to T”
 For example:

47 Computer Programming 10/29/2025


C++ Pointers Declarations
 Pointers variables are variables that points to a
specific address in the memory pointed by another
variable.
 For example: int *p; int *p, *q;
// or, // for many pointers
int* p; int* p, q;
 The statement above defines a pointer variable p,
which holds the memory address.
 The asterisk ‘*’ is a dereference operator which
means pointer to.
 Here, pointer p is a pointer to int, i.e., it is pointing
to an integer value in the memory address.
 If ptr is a pointer then, *ptr gives the value of
10/29/2025
48
that address. Computer Programming
Example - Pointer

49
example

int main()
{
int var = 20;
//declare pointer variable
int *ptr;
//note that data type of ptr and var must be same
ptr = &var;
// assign the address of a variable to a pointer
cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value atOutput:
*ptr = " << *ptr << "\n";
return 0; Value at ptr =
0x7ffcb9e9ea4c
}
Value at var = 20
50 Computer
Value at Programming
*ptr = 20 10/29/2025
Example 2: C++ Pointers
#include <iostream>
using namespace std;
int main(){
int *pc, c;
c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
pc = &c; // Pointer pc holds the memory address of variable c
cout << "Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the pointer pc holds (*pc): " << *pc << endl << endl;
c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the pointer pc holds (*pc): " << *pc << endl << endl;
*pc = 2;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
return 0;
}
51 Computer Programming
10/29/2025
 When c = 5; the value 5 is stored in the address of
variable c - 0x7fff5fbff8c.
 When pc = &c; the pointer pc holds the address of c
- 0x7fff5fbff8c, and the expression (dereference
operator) *pc outputs the value stored in that
address, 5.
 When c = 11; since the address pointer pc holds is
the same as c - 0x7fff5fbff8c, change in the value of
c is also reflected when the expression *pc is
executed, which now outputs 11.
 When *pc = 2; it changes the content of the address
stored by pc - 0x7fff5fbff8c. This is changed from 11
to 2. So, when we print the value of c, the value is 2
Address of c (&c): 0x7fff5fbff80c
Output:
as well.
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2
52
Computer Programming 10/29/2025
Be careful !!!
Suppose, you want pointer pc to point to the address of c.
Then,
int *pc, c = 5;

pc=c; // Wrong! pc is address whereas, c is not an address.


*pc=&c; // Wrong! *pc is the value pointed by address, but &c
is an address.

// In both of the above cases, pointer pc is not pointing to the


address of c.

pc=&c; // Correct! pc is an address and, &c is also an address.


*pc=c; // Correct! *pc is the value pointed by address and, c is
also a value.

// In both of the above cases, pointer pc is pointing to the


address of c.
53 Computer Programming
10/29/2025
Exercises: Pointers
1. Write a program that asks the user to enter
integers as inputs to be stored in the variables
'a' and 'b' respectively. There are also two
integer pointers named ptrA and ptrB. Assign
the values
int main(){of 'a' and 'b' to ptrA and ptrB
int a;
respectively,
int b;
and display them.
cout << "Enter value of A: ";
cin >> a;
cout << "Enter value of B: ";
cin >> b;
int *ptrA=&a;
int *ptrB=&b;
cout << "Value of ptrA is " << *ptrA << " sored in address
"<< ptrA<<"\n";
cout << "Value of ptrB is " << *ptrB <<" sored in address "<<
ptrB<<"\n";
54
return 0;
Exercises: Pointers
2. Write a program that asks the user to enter
two integer values and calculate their sum
using pointers.
int main(){
int a,b,sum;
cout << "Enter value of num1: ";
cin >> a;
cout << "Enter value of num2: ";
cin >> b;
int *ptr1;
int *ptr2;
ptr1=&a;
ptr2=&b;
sum = *ptr1 + *ptr2;
cout << "the sum: "<<sum;;
return 0;
}
55
?
56

You might also like