0% found this document useful (0 votes)
2 views72 pages

Dfc20303 - Chapter 4 (Array, Pointer Structure) (1)

Chapter 4 of the document covers programming fundamentals focusing on arrays, pointers, and structures in C++. It explains the definitions, uses, and relationships between these concepts, including how to declare and manipulate them in code. Additionally, it provides exercises and examples to reinforce understanding and application of these programming elements.

Uploaded by

Siva Kumar
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)
2 views72 pages

Dfc20303 - Chapter 4 (Array, Pointer Structure) (1)

Chapter 4 of the document covers programming fundamentals focusing on arrays, pointers, and structures in C++. It explains the definitions, uses, and relationships between these concepts, including how to declare and manipulate them in code. Additionally, it provides exercises and examples to reinforce understanding and application of these programming elements.

Uploaded by

Siva Kumar
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/ 72

DFC20303

PROGRAMMING
FUNDAMENTALS
CHAPTER 4
ARRAY, POINTER AND STRUCTURE
01 05
COURSE LEARNING DESCRIBE THE USE OF
OUTCOME STRUCTURES

TABLE OF 02 EXPLAIN THE USE OF

CONTENT
ARRAYS

03 SHOW PROGRAM USING THE


CONCEPT OF POINTER

04
IDENTIFY THE RELATIONSHIP
BETWEEN POINTER AND ARRAY
COURSE LEARNING
OUTCOMES
CLO 1:
Apply programming elements and articulate how they are
used to achieve a working program. (C3, PLO2)

CLO 2:
Demonstrate appropriate algorithm based on well-defined
problem using C++ programming language. (P3, PLO3)
02
EXPLAIN THE USE OF
ARRAYS
LEARNING OUTCOMES
4.1 Explain the use of arrays
Define an array.
Describe the components of an array :
a. index
b. element
c. size
Explain types of array :
a. One dimensional
b. Two dimensional
Declare one dimensional
Initialize one dimensional array
Illustrate the one dimensional array.
Access individual element of one dimensional array
DEFINE AN ARRAY
DEFINITION
An array is a collection of elements of the same type placed in contiguous memory locations that can
be individually referenced by using an index to a unique identifier.

Most applications require the processing of multiple data items that have common characteristics.

Each array element (individual data item) is referred to by specifying the array name followed by one or
more subscripts / index (position of elements).
CHARACTERISTIC OF ARRAYS
An array holds elements that have the same data type

Array elements are stored in subsequent memory locations

Two-dimensional array elements are stored row by row in subsequent memory locations.

Array name represents the address of the starting element

Array size should be mentioned in the declaration.

Array size must be a constant expression and not a variable.


Size COMPONENTS OF AN ARRAY
char name[6] = {‘N’,’A’,’R’,’U’,’T’,’O’};

Array name

index/
subscripts
(Start with 0
until n-1)
Element
ONE DIMENSIONAL ARRAY
One-dimensional array is an array with one subscript [].

EXAMPLE
char title [7];
float price[100];
int number[5];

SYNTAX
DataType arrayName [size];
ONE DIMENSIONAL ARRAY
Example of array with default value of zero.

If array declared with less, the


remaining elements are set to
their default values (which for
fundamental types, means
they are filled with zeroes).
ONE DIMENSIONAL ARRAY
INITIALIZATION
You must assign an initial value to the array elements before using them.
Example :

float Height[3]={145.5, 169.8, 179.0};


ONE DIMENSIONAL ARRAY
ACCESS ELEMENT
The values of any of the elements in an array can be accessed just like the value of a
regular variable of the same type.

The syntax is:


ArrayName[index];

Example:
int Sem[] = {2, 5, 6, 4, 7, 3};
The following statement access the value in the third
element of Sem:

Sem [2]; the third element was accessed


ONE DIMENSIONAL ARRAY
Example 1
ONE DIMENSIONAL ARRAY
Example 2 Example 3
EXERCISES 1. Identify:
Array name
Array size
Answer all question based on the illustration below:
Array element
Array index

2. Identify Element for


balance[3]
balance [0]
BALANCE[5]

3. Identify Result if this statement


executed:
cout<<balance[1] * balance[4];
EXERCISES
Write a C++ program based on the statement below:

Create an integer array name ITEM with SIze 3


Assign value to array ITEM with 100, 150, 200
Using for loop, total up all the values.
Display the total of values and
Display values for ITEM[0] * ITEM[1].
03
SHOW PROGRAM
USING THE CONCEPT OF
POINTER
LEARNING OUTCOMES
4.2 Show program using the concept of pointer
Define pointer.
Identify the syntax to declare pointer
Assign the address of variable to pointer
Manipulate the value of variable using pointer
Apply new and delete operators
Design, write, run, test and debug program using pointer.
DEFINE POINTER
DEFINITION
A pointer is a variable that stores/ holds the memory address of another variable that have same
type.

What is a memory address?


Every variable is located under unique location within a computer's memory and this unique location
has its own unique address.

Reminder

A pointer variable, however does not store a value


but store the address of the memory space which
contain the value.
COMPUTER MEMORY
Each variable is assigned a memory slot (the size depends on the data type) and the variable’s data is
stored there.

int a = 100;
int *p;
p = &a;
REASON WHY USE POINTER
To call a function by reference so that the data passed to the function can be changed inside the
function.

To create a dynamic data structure which can grow larger or smaller as necessary.

POINTER DECLARATION
To declare a pointer, asterisk symbol " * " needs to be add and located after variable type and before a
pointer name.

int *ptr;
data_type *pointer_name; double* ptr;
float * ptr;
POINTER DECLARATION
Consider the following declaring variables of Pointer:

int *numberPtr, number = 20;


*numberPtr = &number
POINTER OPERATOR

*
It returns the contents of the memory
location pointed to. The indirection
&
It returns the address of the memory where
a variable is located. We called it Address
operator is also called dereferencing operator.
operator.

int *x;
int c=100; int *x;
int p; int c=100;
x=&c; x=&c;
p=*x;
POINTER OPERATOR
* INDIRECTION/DEREFERENCING OPERATOR
We can access to the value stored in the variable pointed to by using the dereferencing operator
(*).

int a = 100;
int *p = &a;
cout << a << endl;
cout << &a << endl;
cout << p << " " << *p << endl; Result is:
cout << &p << endl; 100
**A pointer is also a variable, so it has its own memory address 1024
1024 100
1032
POINTER OPERATOR
& ADDRESS OPERATOR
We can access the address of value stored in the variable pointed to by using the address
operator (&).

int a, b;
a = 88;
b = 100;

cout << "The address of a is: " << &a << endl; Result is:
cout << "The address of b is: " << &b << endl; The address of a is: 1020
The address of b is: 1024
ASSIGN AN ADDRESS OF VARIABLE TO POINTER

To get the
address of a Since pointers only hold
variable, we can int nvalue = 5; addresses, when we
assign a value to a pointer,
use the address
int *ptr = &nvalue; the value has to be an
of operator (&):
address
ACCESSING THE VALUE AT THE MEMORY ADDRESS
HELD BY A POINTER

int nValue = 5;
int *pnPtr = &nValue; //assign address of nValue to pnPtr
Process accessing a variable's value
by a pointer is called indirection, since
the value of variable is accessed cout<<*pnPtr<<endl; //print the value of pnPtr pointed to
indirectly. cout<<pnPtr<<endl; //print the address that pnPtr is
holding
REFERENCE VARIABLES
A reference is an additional name to an existing memory location
REFERENCE VARIABLES
A reference variable serves as an alternative name for an object.

int m = 10;
int &j = m; // j is a reference variable

cout <<“value of m = “ << m << endl; //print 10

j = 18;

cout <<“value of m = “ << m << endl; // print 18


MANIPULATE THE VALUE OF VARIABLES USING
POINTER
Same as accessing the value at the int *x;
memory address held by pointer by int c = 200;
indirection, the indirection can also int p;
be used to manipulate variable's
value.
x = &c;
p = *x;

cout<<"The address of the memory location of x:"<< x <<endl;


cout<< "The contents of the pointer x:" << *x << endl;
cout<< "The contents of the variable p:" << p << endl;
MANIPULATE THE VALUE OF VARIABLES USING
POINTER
EXERCISE

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 of 'a' and 'b'
to ptrA and ptrB respectively, and display them.
SOLUTION
#include <iostream>
using namespace std;

int main()
{
int a; int b;
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";

return 0;
}
MEMORY ALLOCATION

int main() int main()


{ {
int a[200]; int* ptr;
… ptr = new int[200];
} …
delete [] ptr;
}
NEW OPERATOR

The new operator


requests for the
SYNTAX
memory allocation create new operator
in heap. If the pointer_variable = new datatype;
sufficient memory
is available, it
initializes the
initialize the memory
memory to the pointer_variable = new datatype(value);
pointer variable
and returns its allocate a block of memory
address. pointer_variable = new datatype[size];
NEW OPERATOR
Consider the following declaring variables of pointer using new operator:

int *p = new int;


NEW OPERATOR
Consider the following declaring variables of pointer using new operator:

int *bobby;
bobby = new int [5];

In this case, the system dynamically assigns space for


five elements of type int and returns a pointer to the
first element of the sequence, which is assigned
to bobby
Now, bobby points to a valid block of memory with bobby[0]
space for five elements of type int. The 1st element or
*bobby
pointed by bobby can be accessed either with an
expression:
DELETE OPERATOR

The delete operator is SYNTAX


used to deallocate the
memory. User has privilege create delete operator
to deallocate and free delete pointer_variable;
space the created pointer
variable by this delete deallocate a block of memory
operator. delete[ ] pointer_variable;
DELETE OPERATOR
Consider the following declaring variables of pointer using delete operator:

int* p = new int;


*p = 10;
delete p;
EXAMPLE PROGRAM CODE USING NEW AND DELETE
OPERATOR
#include <iostream>
using namespace std;
int main ()
{
double* pvalue; // Pointer declaration
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // Free up the memory


cout << "Value of pvalue : " << *pvalue << endl;
return 0;
}
04
IDENTIFY THE
RELATIONSHIP BETWEEN
POINTER AND ARRAY
LEARNING OUTCOMES
4.3 Describe the relationship between pointer and array
Identify the relationship between pointer and array
Apply pointer to manipulate the elements of array
Solve a given problem by writing program, running, testing and debugging using
pointer and array
ARRAY VS POINTER
An array name is a constant pointer to the first element of the array.

Pointers can do array subscripting operations. The pointer can be set to


the address of the first element of the array.

Reminder

double *p; Once you store the address of


first element in p, you can access
double balance[10]; array elements using *p, *(p+1), *
p = balance; (p+2) and so on.
ARRAY VS POINTER
p = balance; *(p + 3)
// assign address of array balance to // Array element balance[ 3 ] can alternatively be
p referenced with the pointer expression

p = &balance[0]; *(p + 3)
// also assigns address of array The preceding notation is referred to as
balance to p pointer/offset notation. The parentheses are
necessary, because the precedence of * is higher
than the precedence of +.

Without the parentheses, the above expression


would add 3 to the value of *p.
ARRAY VS POINTER
double *bptr;
double c[12] = {-45,6,0,72,1543,-89,0,62,-3,1,6453,78};
bptr = c;
ARRAY VS POINTER
Accessing array elements with pointers Pointers can be subscripted (pointer /
subscript notation
c[n] --> *(bptr + n)
c[3] --> bptr[3]
Addresses array elements with pointers

&c[3] --> bptr + 3

Array name can be treated as pointer

c[3] --> *(c + 3)


ARRAY VS POINTER
ARRAY VS POINTER
ARRAY VS POINTER
ARRAY VS POINTER
ARRAY VS POINTER: EXERCISE 1
Write a program to display address of each element of an array with size 5 that
hold value 12, 14, 16, 18, 20 using array and pointer. Then display the value of 3rd
elements and add 10 to the 2nd element.

EXPECTED OUTPUT
ARRAY VS POINTER: EXERCISE 2
Complete the program code below, run and show the output:

#include <iostream>
using namespace std;
int main()
{
int Number[] = { 5,10,15,20,25 };
int *pNumbers = Number;
//a. Write a command to display the 4th element of array Number

//b. Write a command to display 1st element using pointer name

//c. write a command to display the sum of 2nd element is 20

//d. write a command to display the last element in array Number using pointer
return 0;
}
05
DESCRIBE THE USE OF
STRUCTURES
LEARNING OUTCOMES
4.4 Demonstrate the use of structures
Describe structures
Identify the difference between structure and arrays.
Define and declare a structure
Assign values to a structure variable.
Access member variables of a structure.
Apply the coding standards and best practices for structure.
Illustrate structures in memory.
Solve a given problem by writing program
Access member variables of a structure using pointer.
INTRODUCTION TO STRUCTURE
Structure is a collection of related data items, possibly of different types.
A structure type in C++ is called struct.
Structure can be referred to using the same name.
The preceding structure definition does not reserve any space in memory but the definition
creates a new data types that is used to declare variables.

Data structure
A data structure is a group of data elements grouped together under one name. These data
elements, known as members, can have different types and different lengths.
INTRODUCTION TO STRUCTURE
Structures hold data that belong together.
Examples:

Student record: student id, name, major, gender, start year, …


Bank account: account number, name, currency, balance, …
Address book: name, address, telephone number, …

In database applications, structures are called records.


DIFFERENCE BETWEEN STRUCTURE AND ARRAYS
STRUCTURE DECLARATION
Data structures are declared in C++ using the following syntax:

EXAMPLE
struct structure_name
struct addressBook
{
{
member_type1 member_name1;
string name;
member_type2 member_name2; string address;
member_type3 member_name3; string phone;
…….. };
};
STRUCTURE DECLARATION
Let us assume that we want to create an account. We would need the following information:
STRUCTURE DECLARATION

Structures can combine


data of different types
DECLARE STRUCTURE VARIABLE
Data structures variable are declared in C++ using the following syntax:

struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
……..
}object name/structure variables;
DECLARE STRUCTURE VARIABLE
Data structures variable are declared in C++ using the following syntax:
DECLARE STRUCTURE VARIABLE
Declare a structure named Student that has ID of 10 characters, name of 40 characters, and marks
of integer type. Then, declare an array called Students (object) with the size 25 for the structure.
ASSIGN VALUES TO A STRUCTURE VARIABLES
Given the facts about a computer, write the structure.
Manufacturer: HP
Memory: 512
Price: 2199.90
ASSIGN VALUES TO A STRUCTURE VARIABLES
Given the information structure for workers as follows:
struct infopekerja
{ Write programming statement to assign the following workers
information into the pekerja[9] variable:
string nama;
float gaji; Nama: Ali

} pekerja [10];
Gaji: 650.00
ANSWER!
ACCESS VALUES IN A STRUCTURE VARIABLE
Members of a structure are accessed using the member access operators :–
the dot operator ( . ) and the arrow operator ( -> )

Example using dot (.) operator:


To print member hour of timeObject, use the statement:
cout<< timeObject.hour;
To print member hour of the Time object referenced by timeRef, use the
statement:
cout<< timeRef.hour;
ACCESS VALUES IN A STRUCTURE VARIABLE
Example using arrow (->) operator:
Assume that the pointer timePtr has been declared to point to a Time object, and
that the address of timeObject has been assigned to timePtr.
To print member hour of timeObject with pointer timePtr, use the statement
cout << timePtr -> hour;
The expression timePtr->hour is equivalent to (*timePtr).hour
NESTED STRUCTURE
Structures in C++ can be nested (one structure can be declare within another
structure).

Nesting one structure within another saves time when the program needs similar
structures.
NESTED STRUCTURE

output‌
EXAMPLE PROGRAM USING STRUCTURE

output‌
EXERCISE
By using struct, write a program which will accept name, ID number and test marks
from Test 1- Test 5. Your program should calculate and display the total and
average of marks for the students.
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy