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

data structure and algorithm chapter 1

Uploaded by

hithere1234
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 views

data structure and algorithm chapter 1

Uploaded by

hithere1234
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/ 94

Review of C++ Concepts

DSA- Chapter One

1
Content

▪ Functions
▪ Arrays
▪ Pointers
▪ dynamic memory allocation
▪ Structure

4/19/2021 2
1.Function

4/19/2021 3
Functions in C++

▪ Function is a logically grouped set of statements that


perform a specific task.
▪ In C++ program, a function is created to achieve something.
▪ Every C++ program has at least one function
i.e. main() where the execution of the program starts.
▪ Code within the function starts to execute when the
function is called from other functions.

4/19/2021 4
Why functions?

▪ Avoid repetition of codes.


▪ Increases program readability.
▪ Divide a complex problem into simpler ones.
▪ Reduces chances of error.
▪ Modifying a program becomes easier by using function.

4/19/2021 5
Types of Functions

– Types of Functions in C++, there are two types of functions


in C++.
▪ Library Functions
– Library functions are pre-defined functions in C++.
▪ User-defined Functions
– We can also define our own functions in C++.

4/19/2021 6
Components of Function

▪ A function usually has three components. They are:


– Function Prototype/Declaration
– Function Definition
– Function Call

4/19/2021 7
Function Prototype/Declaration

▪ Function declaration is a statement that informs the


compiler about
– Name of the function
– Type of arguments
– Number of arguments
– Type of Return value

4/19/2021 8
Syntax for function declaration
▪ We declare a function as follows
return_type function_name ( parameters ) ;
– return_type: any valid data type or void (A function with void as return type don’t return
any value. )
– function_name: any valid cpp identifier
– parameters: zero or more input to the function(separated by comma if more than 1)
▪ Examples:
– float average( int num1, int num2 ); /*function name = average, receives two integers as
argument and returns float*/
– int product(int,int); /*function name = product, receives two integers as argument and
returns an integer*/

▪ Note:
– A function declaration doesn’t require name of arguments to be provided, only type of the arguments
can be specified.
4/19/2021 9
Function Definition

▪ Function definition consists of the body of function.


▪ The body consists of block of statements that specify what task is to be
performed.
▪ When a function is called, the control is transferred to the function definition.

4/19/2021 10
Syntax for function definition

▪ Syntax for defining a function is


return_type function_name ( [parameters] )
{
//code
}

4/19/2021 11
Example
– Let's see the average function that we defined earlier.

float average( int num1, int num2 )


{
float avg; /* declaring local variable */
avg = ( num1 + num2 )/2.0;
return avg; /* returning the average value */
}
▪ Note:
– While defining functions, it is necessary to specify the parameter
type along with the parameter name.
▪ Therefore, we wrote 'int' along with num1 and num2.
– The value the function returns must comply with the return type of
the function
▪ return avg; - returns value of type float. 4/19/2021 12
Calling Function
▪ A function call can be made by using a call statement.
▪ A function call statement consists of function name and required
argument enclosed in round brackets.
▪ To use a function, we need to call it.
– Once we call a function, it performs its operations and after that, the control
again passes to the caller function.
▪ Syntax:
function_name ( parameters ) ;
▪ Example:
– If we want to call our average function, we can do it as follows
average( num1, num2 );
4/19/2021 13
Function Call

▪ A function can be called by two ways. They are:


– Call by value
– Call by reference

4/19/2021 14
Call by value

▪ When a function is called by value, a copy of actual argument is


passed to the called function.
▪ The copied arguments occupy separate memory location than the
actual argument.
▪ If any changes done to those values inside the function, it is only
visible inside the function.
▪ Their values remain unchanged outside it.

4/19/2021 15
Example: call bay value

4/19/2021 16
Call by reference

▪ In this method of passing parameter, the address of argument is


copied instead of value.
▪ Inside the function, the address of argument is used to access the
actual argument.
▪ If any changes is done to those values inside the function, it is visible
both inside and outside the function.

4/19/2021 17
Example: call by reference
#include <iostream>
void swap(int &x, int &y) // function definition
Using namespace std;
void swap(int &, int &); // function prototype
{
int temp;
int main() {
temp = x;
int a,b; x = y;
cout<<"Enter two numbers: "; y = temp;
cin>>a>>b; }
cout<<"Before swapping”;; Sample Output:
cout<<"a =“<<a<<endl; Enter two numbers: 12 35
cout<<"b =“<<b<<endl; Before swapping
a = 12
swap(a,b); // function call by reference b = 35
cout<<"After swapping\n"; After swapping
cout<<"a =“<<a<<endl; a = 35
b = 12
cout<<"b =“<<b<<endl; return 0; } 4/19/2021 18
Variable Scope
▪ Variable Scope is a region in a program where a variable is declared
and used.
▪ Depending on the region where variables are declared and used,
there are two types of variables
– Local variables
▪ Variables that are declared inside a function or a block are called local variables and
are said to have local scope.
▪ These local variables can only be used within the function or block in which these are
declared.
▪ Example: variables in the previous example programs
– Global variables
▪ Variables that are defined outside of all the functions and are accessible throughout
the program are global variables and are said to have global scope.
▪ Once declared, these can be accessed by any function in the program.

4/19/2021 19
4/19/2021 20
Example:
#include <iostream>
using namespace std;
int g = 10; Here, g is a global variable , since we declared 'g' outside of
all the functions and gave it a value in the function.
void func1(){
g = 20;
cout << g << endl; What is the output?
}
int main(){
func1();
g = 30;
cout << g << endl;
return 0;
}
4/19/2021 21
What if there exists a local variable with the same
name as that of global variable inside a function?

/*CPP program to illustrate scope of


local variables and global variables what will be the output? 2 or 5?
together*/
#include<iostream> • When two variable with same name are defined
using namespace std; then the compiler produces a compile time error.
// global variable
int global = 5;
• But if the variables are defined in different scopes
then the compiler allows it.
// main function • Whenever there is a local variable defined with
int main() same name as that of a global variable then
{ the compiler will give precedence to the local
// local variable with same
// name as that of global variable
variable.
int global = 2;
cout << global << endl; • Hence, the output is 2
}
4/19/2021 22
How to access a global variable when there
is a local variable with same name?

// C++ program to show that we can access a global • We use the scope resolution operator
// variable using scope resolution operator :: when (::) to access global variable in the
// there is a local variable with same name
presence of local variable having same
#include<iostream> Output: name with the global variable
using namespace std; Value of global x is 0
Value of local x is 10
int x = 0; // Global x • In C++, scope resolution operator is ::.

int main() { • It is used for the following purposes.


int x = 10; // Local x • To access a global variable when
there is a local variable with same
cout << "Value of global x is " << ::x;
name:
cout<< "\nValue of local x is " << x; • To define a function outside a class.
return 0; • To access a class’s static variables.
• For namespace etc
} 4/19/2021 23
2.Arrays
Arrays

▪ An array is a collection of data elements that are of the same type


(e.g., a collection of integers, collection of characters, collection
of doubles).

4/19/2021 25
Arrays
▪ 1-dimensional array.

▪ Two dimensional array

▪ It can also be Multi-dimensional if the data is more than two dimensional


4/19/2021 26
Applications of arrays

▪ Given a list of test scores, determine the average,


maximum and minimum scores.
▪ Read in a list of student names and rearrange
them in alphabetical order (sorting).
▪ Given the height measurements of students in a
class, output the names of those students who are
taller than average.

4/19/2021 27
Array Declaration
▪ Syntax:
<type> <arrayName>[<array_size>]
Ex. int Ar[9];
▪ The array elements are all values of the type <type>.
▪ The size of the array is indicated by <array_size>, the number of
elements in the array.
▪ <array_size> must be an int constant or a constant expression.
▪ Note that an array can have multiple dimensions.
4/19/2021 28
Multi-dimensional array declaration

▪ Syntax:
<type> <arrayName>[<num_rows>] >[<num_columns>]
Ex. int Ar[9][9];

4/19/2021 29
Accessing Array Elements
▪ Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
▪ Subscript(indexing):
– To access an individual element we must apply a subscript to array named Ar.
– A subscript is a bracketed expression.
▪ The expression in the brackets is known as the index.
– First element of array has index 0. Ar[0]
– Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
– Last element has an index one less than the size of the array. Ar[9]
▪ Caution: Incorrect indexing is a common error.
4/19/2021 30
Subscripting

// array of 10 uninitialized ints


int Ar[10];

Ar[3] = 1; --
int x = Ar[3];
1 --

-- -- --

0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
4/19/2021 31
Array Element Manipulation

▪ Consider
int Ar[10], i = 7, j = 2, k = 4;
Ar[0] = 1;
Ar[i] = 5;
Ar[j] = Ar[i] + 3;
Ar[j+1] = Ar[i] + Ar[0];
Ar[Ar[j]] = 12;
cin >> Ar[k]; // where the next input value is 3

0 1 2 3 4 5 6 7 8 9
Ar 1 -- 8 6 3 -- -- 5 12 --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]

4/19/2021 32
Array Initialization Ex.
int Ar[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 6 5 4 3 2 1 0

– It can also be initialized like:

int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

– Once it is initialized, its values can be altered


Ar[3] = -1;
6 -1

0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 -1 5 4 3 2 1 0
4/19/2021 33
Example: Printing arrays

To print an array, you have to print each element in the array


using a loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)


{
cout << Ar[i] << " ";
}

4/19/2021 34
Fill array from keyboard
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
} 4/19/2021 35
Copying Arrays

▪ Can you copy array using a syntax like this?


list = myList;

▪ This is not allowed in C++. You have to copy individual elements from one array
to the other as follows:

for (int i = 0; i < ARRAY_SIZE; i++)


{
list[i] = myList[i];
}

4/19/2021 36
Summing All Elements

Use a variable named total to store the sum.


Initially total is 0.
Add each element in the array to total using a loop like this:

double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
} 4/19/2021 37
Finding the Largest Element

▪ Use a variable named max to store the largest element.


▪ Initially max is myList[0].
▪ To find the largest element in the array myList, compare each element in myList with
max, update max if the element is greater than max.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max) max = myList[i];
}
4/19/2021 38
Finding the index of the largest
element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
4/19/2021 39
Shifting Elements

Int myListSize= 10;


double temp = myList[0]; // Retain the first element
// Shift elements left
for (int i = 1; i < myListSize; i++)
{
myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position
myList[myListSize - 1] = temp;
4/19/2021 40
Passing Array to a Function
▪ In C++, we can pass arrays as an argument to a function. And, also we can
return arrays from a function.
▪ There are two syntax for declaring function with array parameter
1. returnType functionName(dataType arrayName[ ], int size)
Example:
▪ Int sum(int marks[], int size);
2. returnType functionName(dataType arrayName[arraySize])
Example:
▪ Int sum(int marks[5]);

▪ When we call a function by passing an array as the argument, only the


name of the array is used.
– functionName(arrayName); //note there is no[ ] during function call

4/19/2021 41
Example
void display(int m[5]) {

cout << "Displaying marks: " << endl;

// display array elements

for (int i = 0; i < 5; ++i)

cout << "Student " << i + 1 << ": " << m[i] << endl;

int main() {

// declare and initialize an array

int marks[5] = {88, 76, 90, 61, 69};

// call display function and pass array as argument with no size and [ ] operator

display(marks);

return 0;
4/19/2021 42
}
Exercise 1: What is the output?

4/19/2021 43
Exercises

▪ Find the average of an integer array


– Read 10 integers from the keyboard
– Calculate and display the average value

▪ Find second largest element in an given array of integer


▪ Find the largest three elements in an array

4/19/2021 44
3.Pointers

4/19/2021 45
Computer Memory

▪ Each variable is assigned a memory slot (the size depends on the


data type) and the variable’s data is stored there

Memory address: 1020 1024 1032

… … 100 … 1024 …
a
Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024

4/19/2021 46
Pointers

▪ A pointer is a variable used to store the address of a memory cell.


▪ We can use the pointer to reference this memory cell

Memory address: 1020 1024 1032

… … 100 … 1024 …
integer
pointer
4/19/2021 47
Pointer Types

▪ Pointer
– C++ has pointer types for each type of object
▪ Pointers to int objects
▪ Pointers to char objects
▪ Pointers to user-defined objects
– Struct type(e.g., Student)
– Class type
– Even pointers to pointers
▪ Pointers to pointers that points to int objects

4/19/2021 48
Pointer Variable

▪ Declaration of Pointer variables


type* pointer_name;
//or
type *pointer_name;
where type is the type of data pointed to (e.g. int, char,
double)

Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
4/19/2021 49
Address Operator &

▪ The "address of " operator (&) gives the memory address of the
variable
– Usage: &variable_name
Memory address: 1020 1024

… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
4/19/2021 50
Address Operator &

Memory address: 1020 1024 1032

… 88 100 … … …
a b
#include <iostream>
Result is:
using namespace std;
The address of a is: 1020
void main(){
The address of b is: 1024
int a, b;
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
} 4/19/2021 51
Pointer Variables
Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
int *p = &a;
cout << a << " " << &a <<endl;
cout << p << " " << &p <<endl; Result is:
100 1024
1024 1032

▪ The value of pointer p is the address of variable a


▪ A pointer is also a variable, so it has its own memory address
4/19/2021 52
Dereferencing Operator *

▪ We can access to the value stored in the variable pointed to by using


the dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
4/19/2021 53
Pointer to Pointer

What is the output?

58 58 58

4/19/2021 54
Don’t get confused
▪ Declaring a pointer means only that it is a pointer:
– int *p;

▪ Don’t be confused with the dereferencing operator, which is also written with an
asterisk (*).
– They are simply two different tasks represented with the same sign

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

int *p1 = &a, *p2, *p3 = &c;

p2 = &b; // p2 points to b
Result is:
p2 = p1; // p2 points to a 888
b = *p3; //assign c to b

*p2 = *p3; //assign c to a

cout << a << b << c; 4/19/2021 55


A Pointer Example
The code Box diagram Memory Layout
void doubleIt(int x, int * p)
main
{
*p = 2 * x; p 8192
a 18 (8200)
}
doubleIt
int main() x 9
{ (8196)
int a = 16;
a 18 main
doubleIt(9, &a); doubleIt (8192)
cout<<“a gets “<<a;
x 9
return 0;
}
a gets 18 p

4/19/2021 56
Another Pointer Example
#include <iostream>
Result is
using namespace std;
value1==10 / value2==20
int main (){
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
} 4/19/2021 57
Reference Variables
A reference is an additional name to
an existing memory location
Pointer: Reference:

x 9 x
9
ref

ref

int x = 9;
int x=9;
int &ref = x;
int *ref;
ref = &x;
4/19/2021 58
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;
value of m = 10
//print 10
value of m = 18
j = 18;
cout << “value of m = “ << m << endl;
// print 18 4/19/2021 59
Reference Variables

▪ A reference variable always refers to the same object.

▪ Assigning a reference variable with a new value actually


changes the value of the referred object.

▪ Reference variables are commonly used for parameter


passing to a function
4/19/2021 60
Traditional Pointer Usage

void IndirectSwap(char *Ptr1, char *Ptr2){


char temp = *Ptr1;
*Ptr1 = *Ptr2;
*Ptr2 = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(&a, &b);
cout << a << b << endl;
return 0;
}
4/19/2021 61
Pass by Reference

void IndirectSwap(char& y, char& z) {


char temp = y;
y = z;
z = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(a, b);
cout << a << b << endl;
return 0;
}

4/19/2021 62
NULL pointer

▪ NULL is a special value that indicates an empty pointer


▪ If you try to access a NULL pointer, you will get an error
int *p;
p = 0;
cout << p << endl; //prints 0
cout << &p << endl;//prints address of p
cout << *p << endl;//Error!
4/19/2021 63
Pointers in Array
▪ Pointer to the array holds the address of the first element of the array i.e., array[0].
▪ Similarly, array name is a pointer to the first element of the array.
▪ If p is a pointer to the array age, then it means that p(or age) points to age[0].
int age[50];
int *p;
p = age;
– The above code assigns the address of the first element of age to p.
– Now, since p points to the first element of the array age, *p is the value of the first element of the
array.

▪ So, *p is age[0], *(p+1) is age[1], *(p+2) is age[2].


– Similarly, *age is age[0] ( value at age ), *(age+1) is age[1] ( value at age+1 ), *(age+2) is age[2] (
value at age+2 ) and so on.
4/19/2021 64
4.Dynamic Memory Allocation

4/19/2021 65
Memory Management

▪ Static Memory Allocation


– Memory is allocated at compilation time
▪ Dynamic Memory
– Memory is allocated at running time

4/19/2021 66
Static vs. Dynamic Objects

Static object Dynamic object


(variables as declared) – Memory is acquired by program
– Memory is acquired automatically with an allocation request
▪ new operation

– Dynamic objects can exist beyond


– Memory is returned automatically the function in which they were
when object goes out of scope allocated

– Object memory is returned by a


de-allocation request
▪ delete operation
4/19/2021 67
Memory Allocation

new
delete
{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
4/19/2021 68
Object (variable) creation: New

Syntax
ptr = new SomeType;
where ptr is a pointer of type SomeType

Example
int* p = new int;

Uninitialized int variable

4/19/2021 69
Object (variable) destruction: Delete

Syntax
delete p;
storage pointed to by p is returned to free store and p is now undefined

Example
int* p = new int;
*p = 10;
delete p;

p 10
4/19/2021 70
Array of New: dynamic arrays

▪ Syntax
SomeType *P = new SomeType[Expression];
– Where
▪ P is a pointer of type SomeType
▪ Expression is the number of objects to be constructed -- we are making an array

▪ Because of the flexible pointer syntax, P can be considered to be an


array

4/19/2021 71
Example
Dynamic Memory Allocation
 Request for “unnamed” memory from the Operating System

int *p, n=10; new

p = new int; p
p = new int[100];
new

p
new
p = new int[n]; p
4/19/2021 72
Memory Allocation Example

main() Want an array of unknown size ?


{
cout << “How many students? “;
cin >> n;
int *grades = new int[n];
for(int i=0; i < n; i++){
int mark;
cout << “Input Grade for Student” << (i+1) << “ ? :”;
cin >> mark;
grades[i] = mark;
}
. . .
printMean( grades, n ); // call a function with dynamic array
. . .
} 4/19/2021 73
Freeing (or deleting) Memory

4/19/2021 74
Caution 1: Memory Leak Problem
int *A = new int [5];
for(int i=0; i<5; i++)
A[i] = i;  2

A 0 1 2 3 4

These locations cannot be


A = new int [5]; accessed by program

A 0 1 2 3 4

— — — — —

4/19/2021 75
Caution 2; Dangling Pointer Problem

int *A = new int[5];


for(int i=0; i<5; i++)
A[i] = i;
int *B = A;
A
0 1 2 3 4
B

Locations do not belong to program


delete [] A;
A —

B[0] = 1; // illegal! ?
B
4/19/2021 76
5. Structures

4/19/2021 77
Structure

▪ A structure is a user-defined data type in C/C++.


▪ It is used to store together elements of different data
types.
▪ A structure creates a data type that can be used to
group items of possibly different types into a single
type.

4/19/2021 78
When we may use structures ?

▪ Suppose you need to store information about a student; like


name, cgpa, and age.
– You can create variables like name, cgpa, and age to store the data
separately.
▪ However, you may need to store information about many
students in the future.
– It means variables for different individuals will be created.
– For example, name1, cgpa1, age1 etc.
▪ To avoid this, it's better to create a struct AND array of struct.

4/19/2021 79
How to create a structure?
Example struct declaration
▪ The ‘struct’ keyword is used to create a
structure. struct Student
▪ The general syntax to create a structure is: {
char name[30];
float cgpa;
struct structureName{
int age;
member1; }s1;
member2;
. In the above example, Student is a structure
with three members. And an instance(variable)
. of the Student structure s1
.
memberN; Note;
• Memory is only allocated after a
} [zero or more structure variables]; variable is added to the struct.
4/19/2021 80
How to declare structure variables?

▪ A structure variable can be declared in either of the two ways


1. With structure declaration or
▪ Example:
– look at the struct declaration on the previous slide, s1 variable is
declared during struct declaration
2. As a separate declaration like basic types.
▪ Example
int main(){
Student s2;
return 0;
}
4/19/2021 81
How to initialize structure members?

▪ Prior to C++ 11, Structure members cannot be initialized with declaration.


▪ Structure members can be initialized using curly braces ‘{}’. For example,
following is a valid initialization.
int main()
{
/*during assigning values to member variables, the order of declaration is followed. */

Student s1 = {“Abebe Kebede”, 3.75, 20};


}

4/19/2021 82
How to access structure elements?

▪ Structure members are accessed using dot (.) operator.


▪ Example
int main(){
/*during assigning values to member variables, the order of declaration is
followed. */
student s1 = {“Abebe Kebede”, 3.75, 20};
S1.cgpa=3.89;
cout<<“cgpa of “<<s1.name<<“is”<<s1.cpga;
}

4/19/2021 83
Pointers to Structure
▪ It's possible to create a pointer that points to a structure.
▪ It is similar to how pointers pointing to native data types like int, float,
double, etc.
▪ Example • The ‘.’ operator can also be used with
struct pointer, but can look clumsy;
int main(){
student s1 = {“Abebe Kebede”, 3.75, 20}; • Example:
cout<<(*sp).cgpa ;
Student *sp=&s1; • Note:
• () is required due to operator
sp->cgpa=3.89; precedence
cout<<“cgpa of “<<sp->name<<“is”<<sp->cpga;
}
4/19/2021 84
Another Example: structure pointers

4/19/2021 85
Exercise: What is the output ?

4/19/2021 86
Array of Structures

▪ On the previous example of structures, we stored


the data of 3 students.
▪ Now suppose we need to store the data of 100 such
students.
– Declaring 100 separate variables of the structure is
definitely not a good option.
– For that, we need to create an array of structures.

4/19/2021 87
Array of Structures

▪ struct student
{
int roll_no;
string name;
int phone_number;
};
int main()
{
student stud[100];

return 0;
}

4/19/2021 88
Example: read and display details of 5
students

4/19/2021 89
Nested structures
▪ We can nest structures inside structures.

(P.x, P.y)
▪ Examples:
struct point{ (L.p2.x, L.p2.y)
double x, y;
}; (L.p1.x, L.p1.y)
point P;

struct line{ (T.p2.x, T.p2.y)


point p1, p2;
};
line L;

struct triangle{
point p1, p2, p3; (T.p3.x, T.p3.y)
};
triangle T;
(T.p1.x, T.p1.y)
90
Nested structures
point P;
line L;
triangle T;
(4, 11)
P.x = 4;
P.y = 11; (10, 9)
L.p1.x = 2;
L.p1.y = 7; (2, 7)
L.p2.x = 10;
L.p2.y = 9; (6, 5)
T.p1.x = 2;
T.p1.y = 0;
T.p2.x = 6; (8, 3)
T.p2.y = 5;
T.p3.x = 8;
(2, 0)
T.p3.y = 3; 91
C++ Structure and Function
▪ Structures variables can be passed to a function and
returned in a similar way as normal arguments.
Example:
struct_type func_name(struct_type){
.
.
.
return struct_type;
}
92
struct Person

{ char name[50]; Passing and returning structure


variables to/from functions
int age;

float salary; // Function defination


}; Person getData(Person p) {

Person getData(Person); // Function declaration cout << "Enter Full name: ";
cin.get(p.name, 50);
void displayData(Person);
cout << "Enter age: ";
int main() cin >> p.age;
{ cout << "Enter salary: ";
cin >> p.salary;
Person p;
return p;
// Function call with structure variable as an argument }
p = getData(p); void displayData(Person p)
{
displayData(p);
cout << "\nDisplaying Information." << endl;
return 0; cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
}
cout << "Salary: " << p.salary;
93
}
Next Time!
Ch2: Complexity Analysis

4/19/2021 94

You might also like