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

Chapter 4-Computer Programming- Array ,String & Pointer

This document provides an overview of arrays, strings, and pointers in C++. It covers topics such as array types, initialization, accessing elements, and the use of strings and related library functions. Additionally, it includes exercises and examples to illustrate the concepts discussed.

Uploaded by

rajizerihun140
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)
13 views

Chapter 4-Computer Programming- Array ,String & Pointer

This document provides an overview of arrays, strings, and pointers in C++. It covers topics such as array types, initialization, accessing elements, and the use of strings and related library functions. Additionally, it includes exercises and examples to illustrate the concepts discussed.

Uploaded by

rajizerihun140
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/ 49

Computer Programming (CP)

Unit-4
Arrays, Strings and
Pointers

Admas Abtew
Faculty of Computing and
Informatics
Jimma Technology Institute, Jimma

[email protected]
+251912499102
 Looping
Outline
 Introduction to Arrays
 Types of arrays
 Array initialization
 Strings
 Library functions for strings
 Pointers
 Pointer Declaration
1. 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?

CP  Unit 4-Arrays, Strings and Pointers 3


Cont’d…
 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

CP  Unit 4-Arrays, Strings and Pointers 4


Types of Array
 One Dimensional Array
Declaration of arrays
A typical declaration for an array in C++ syntax is:
type arrayName[size];
For 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
 Multi Dimensional Array

CP  Unit 4-Arrays, Strings and Pointers 5


Cont’d…
 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];

CP  Unit 4-Arrays, Strings and Pointers 6


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;
CP  Unit 4-Arrays, Strings and Pointers 7
Cont’d…
 When declaring an array of local scope (within a function), if we do not
specify otherwise, it will not be initialized, so its content is undetermined
until we store some values on it.
 If we declare a global array (outside any function) its content will be
initialized with all its elements filled with zeros. Thus, if in the global scope
we declared:
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:
CP  Unit 4-Arrays, Strings and Pointers 8
Cont’d…
 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};

CP  Unit 4-Arrays, Strings and Pointers 9


Cont’d…
 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];

CP  Unit 4-Arrays, Strings and Pointers 10


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

 We can use loop to manipulate/process an array.

CP  Unit 4-Arrays, Strings and Pointers 11


Cont’d…
Exercise 1
If an array has five elements, what is the highest index of a valid element in
the array?
 Answer: 4

CP  Unit 4-Arrays, Strings and Pointers 12


Cont’d…
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;
}

CP  Unit 4-Arrays, Strings and Pointers 13


Cont’d…
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}

CP  Unit 4-Arrays, Strings and Pointers 14


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

CP  Unit 4-Arrays, Strings and Pointers 15


Bidimensional Arrays
 An array may have more than one dimension. Each
dimension is represented as a subscript in the array.
 A two dimensional array have two subscripts
 A three dimensional array has three subscripts, and so on.

CP  Unit 4-Arrays, Strings and Pointers 16


Cont’d…
syntax is:
type arrayName[rowSize][columnSize];
For example, declaring an array numbers as shown above:

int numbers [3][2];


The data The name 3 is the raw 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.

CP  Unit 4-Arrays, Strings and Pointers 17


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}};

CP  Unit 4-Arrays, Strings and Pointers 18


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.
CP  Unit 4-Arrays, Strings and Pointers 19
Cont’d…
// 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
{ at x[1][1]: 3
for (int j = 0; j < 2; j++) Element at x[2][0]:
{
4 Element at x[2]
cout << "Element at x[" << i
[1]: 5
<< "][" << j << "]: ";
cout << x[i][j]<<endl;
}}
return 0;
CP  Unit 4-Arrays, Strings and Pointers 20
Cont’d…
 Write a C++ program to read a two dimensional square
matrix A and display elements of the matrix to the screen.

CP  Unit 4-Arrays, Strings and Pointers 21


Strings

CP  Unit 4-Arrays, Strings and Pointers 22


String Definition
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

CP  Unit 4-Arrays, Strings and Pointers 23


Cont’d…
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";
char s2[20] = "another example“
In the first case the array would be allocated space for eight characters, that
is space for the seven characters of the string and the null character
In the second case 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.

CP  Unit 4-Arrays, Strings and Pointers 24


Cont’d…

 Some examples of string constants in C++ are:

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

CP  Unit 4-Arrays, Strings and Pointers 25


Cont’d…
 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);
}

CP  Unit 4-Arrays, Strings and Pointers 26


Cont’d…
 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);
}
CP  Unit 4-Arrays, Strings and Pointers 27
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.

CP  Unit 4-Arrays, Strings and Pointers 28


Cont’d…

. 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);
}

CP  Unit 4-Arrays, Strings and Pointers 29


Cont’d…
. #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;
}

CP  Unit 4-Arrays, Strings and Pointers 30


Cont’d…
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 str1[] = "String test";
char str2[] = "Hello";
char one[10];

CP  Unit 4-Arrays, Strings and Pointers 31


Cont’d…
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
system("PAUSE");
return 0;
}

CP  Unit 4-Arrays, Strings and Pointers 32


Cont’d…
. strlen(string) — String Length :

#include <iostream.h>
#include <cstdio.h>
strlen(str) returns the length of
#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);
}

CP  Unit 4-Arrays, Strings and Pointers 33


Cont’d…
 strcat(string_1, string_2) — Concatenation of Strings :

#include <iostream.h>
#include <cstdio.h> The strcat(s1,s2)
#include <cstring.h> function appends s2 to the
int main(){ end of s1. String s2 is
char s1[21], s2[11]; unchanged.
strcpy(s1, “Hello”);
strcpy(s2, “ there”); Displays:

strcat(s1, s2); Hello there


cout << s1 << endl; there
cout << s2 << endl;
return(0);
}

CP  Unit 4-Arrays, Strings and Pointers 34


Cont’d…
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] = "xyz";
output
strcat(str1, str2);
abc
cout << str1 << endl;
abcdef
str1[4] = '\0';
abcdefxyz
cout << str1 << endl;
abcd

CP  Unit 4-Arrays, Strings and Pointers 35


Cont’d…
The function strncat is like strcat except that it copies only a specified number of characters.
Strncat(destination, source, int n);
#include <iostream.h>
#include <cstring.h>
int main() {
output
char str1[30]; abc
strcpy(str1, "abc");
cout << str1 << endl; abcde
strncat(str1, "def", 2);
str1[5] = '\0';
abcdexyz
cout << str1 << endl; abcd
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
system("PAUSE");
return 0;
CP  Unit 4-Arrays, Strings and Pointers 36
Cont’d…
 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
CP  Unit 4-Arrays, Strings and Pointers 37
Cont’d…
#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;
}
CP  Unit 4-Arrays, Strings and Pointers 38
Cont’d…
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;
}
CP  Unit 4-Arrays, Strings and Pointers 39
Cont’d…
 // Comparing strings
#include <iostream.h>
#include <cstring.h>
#include <cstdio.h>
int main(){
char str[80];
cout << “Enter password: “;
gets(str);
if(strcmp(str, “password”)) // strings differ
cout << “Invalid password.\n”;
else cout << “Logged on.\n”;
return(0);
}

CP  Unit 4-Arrays, Strings and Pointers 40


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.

CP  Unit 4-Arrays, Strings and Pointers 41


Example 1: Address in C++
Output:
#include <iostream>
0x7fff5fbff8ac
using namespace std; 0x7fff5fbff8a8
0x7fff5fbff8a4

int main()
{ Note: You may not get the same result on
int var1 = 3; 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 second
cout << &var2 << endl;
by 4-bytes and second address differs from
cout << &var3 << endl;
third by 4-bytes.
return 0;
} This is because the size of integer (variable of
type int) is 4 bytes in 64-bit system.
CP  Unit 4-Arrays, Strings and Pointers 42
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:

CP  Unit 4-Arrays, Strings and Pointers 43


C++ Pointers Declarations

 Pointers variables are variables that points to a specific address


in the memory pointed by another variable.
 For example: int *p; // or, int* p;
int *p, *q; // for many pointers
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 that address.
CP  Unit 4-Arrays, Strings and Pointers 44
Example
int main()
{
int var = 20;
//declare pointer variable
int *ptr;
Output:
//note that data type of ptr and var must be same
ptr = &var; Value at ptr = 0x7ffcb9e9ea4c
Value at var = 20
// assign the address of a variable to aValue
pointer
at *ptr = 20
cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
return 0;
}
CP  Unit 4-Arrays, Strings and Pointers 45
Example2
#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;
}

CP  Unit 4-Arrays, Strings and Pointers 46


Cont’d…
 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 as
well. Address of c (&c): 0x7fff5fbff80c
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5
Output:
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
CP  Unit 4-Arrays, Strings and Pointers 47
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.

int* pc2 = &c; // Correct! pc2 is address pointer, and &c is also address.
CP  Unit 4-Arrays, Strings and Pointers 48
49

You might also like