Download - Medium Level C++
Medium Level C++ Structures, Function, Arrays and Pointers
Engineer Jokhio Sultan Salahuddin Kohistani
Lecturer, CSE, MUET Jamshoro
Structures
We have seen some primitive data types, like int, float
char etc. but C++ also offers some user defined data
types in shapes of structures.*
Structures are user defined data types, which are
combination of several primitive data types.
A structure is a collection of simple variables.
The variables are mostly of different types.
The data items in a structure are called the members of
the structure.
Engr. SDJK, CSE, MUET Jamshoro 2
Definition Syntax & Accessing Structures
struct name-of-struture{
datatype var-name;
datatype var-name;
datatype var-name;
….
};
Accessing:
With dot operator (.)
Structures can be declared and defined outside the main
function.
Engr. SDJK, CSE, MUET Jamshoro 3
Structures Definition
Accessing a Structure variables:
Engr. SDJK, CSE, MUET Jamshoro 4
Structures Cont.
Definition of a structure variable
notice that the format for defining a structure variable is
the same as that for defining a basic built-in data type
such as int:
Engr. SDJK, CSE, MUET Jamshoro 5
Structures in memory
Engr. SDJK, CSE, MUET Jamshoro 6
Combining all those //structures.cpp
#include<iostream>
using namespace std;
struct part //declare a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
Engr. SDJK, CSE, MUET Jamshoro 7
Combining all those //program is continued
int main()
{
part part1; //define a structure variable
part1.modelnumber = 6244;
part1.partnumber = 373;
part1.cost = 217.55F;
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 8
Output
Engr. SDJK, CSE, MUET Jamshoro 9
Structure
All Structures have
their own variables
Engr. SDJK, CSE, MUET Jamshoro 10
Alternative version of the program:
Assigning in a different way
// structures2.cpp
// shows initialization of structure
variables
#include <iostream>
using namespace std;
struct part //specify a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
Engr. SDJK, CSE, MUET Jamshoro 11
//cont.
int main()
{
part part1 = { 6244, 373, 217.55F };
part part2; //define variable
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
part2 = part1; //assign first variable to second
cout << “Model “ << part2.modelnumber;
cout << “, part “ << part2.partnumber;
cout << “, costs $” << part2.cost << endl;
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 12
Functions
A function is the entity in a computer program which groups
the set of statements as a single unit, which when called,
perform some useful operation, like calculating the square of a
number, setting up spaces, asking user to enter something.
A function simply is a collection of statements.
The function could be called from any where of the program.
When the function is called, all the statements inside it are
executed.
Two types
User Defined
Library
Engr. SDJK, CSE, MUET Jamshoro 13
Program (Prototyping/Declaration of the
function)
// functiondemo1.cpp
// demonstrates simple function
#include <iostream>
using namespace std;
void starline(); //function
declaration
// (prototype)
Engr. SDJK, CSE, MUET Jamshoro 14
Program (calling the function).
//Continued from above
int main()
{
starline(); //call to function
cout << "Students Percentage" << endl;
starline(); //call to function
cout<<"12CE01 80"<< endl
<<"12CE02 85"<< endl
<<"12CE03 70"<< endl;
starline(); //call to function
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 15
Program (Function Definition)
// starline()
// function definition
void starline() //function declarator
{
for(int j=0; j<20; j++) //function body
cout << '*';
cout << endl;
}
Engr. SDJK, CSE, MUET Jamshoro 16
Explanation
The program consists of two functions: main() and
starline(). You’ve already seen many programs that use
main() alone.
What other components are necessary to add a function
to the program?
There are three: the function declaration, the call to the
function, and the function definition.
Engr. SDJK, CSE, MUET Jamshoro 17
The Function Declaration
Also called function prototyping.
Just as you can’t use the variable, before you declare it, Simply
you also can’t use a function without first declaring it.
Declaration is necessary, in case you are defining the function
after the main, but if you are defining the function before the
main function, then there is no any need of declaration, you
can directly define and call the function.
The above line is a typical declaration.
Function declaration is terminated with semicolon, this tells
the compiler that, the function will be used inside main, but
will be defined later on.
Sometimes referred as Signature of the function.
Engr. SDJK, CSE, MUET Jamshoro 18
Calling the Function and Its Definition
The main calls the function three times, using the
following statement.
When called, the control is shifted to the function
definition, and all the statements inside the function are
executed.
The Function definition is the actually the collection of
statements that comprises itself.
The First line in the function definition is called the
function declarator, which is followed by the function
body.
Engr. SDJK, CSE, MUET Jamshoro 19
Summary of the Function Components
Engr. SDJK, CSE, MUET Jamshoro 20
Eliminating the declaration #include <iostream>
using namespace std;
void starline()
{
for(int j=0; j<6; j++)
cout << ‘*’<<endl;
}
int main()
{
starline(); //call to function
cout << “HELLO ” << endl;
starline();
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 21
Arrays
As structures are combining different data type variables,
Arrays are entities which are providing feature of
grouping same data types as one single unit.
They are holding homogeneous (similar) type of data.
Can hold few as well as tens of thousands.
Items or members in structures are accessed through
their names with dot operator, but in Arrays we can
access members with their index number which is also an
element number, So accessing elements is easier in arrays.
Arrays can be single dimensional as well as
multidimensional.
Engr. SDJK, CSE, MUET Jamshoro 22
Syntax for single dimensional array
Now this age array will have four elements, starting from age[0] …..
To age [3], total 4 elements. So, the index of first element is zero and
last element is one less than array’s size i.e. 3 = 4-1.
Engr. SDJK, CSE, MUET Jamshoro 23
Arrays inside the memory
Array’s elements inside the memory
are placed sequentially.
The figure shows typical elements
placed inside the array named age[ ].
Now all elements are of integer data
type.
Engr. SDJK, CSE, MUET Jamshoro 24
Accessing array elements
As Array Elements are sequential in nature, they
individually could be easily accessed with the use of loop.
For loop is better to use, as array size is fixed and almost
known in all cases.
So, we can access each element of an array using a for
loop, starting its counter variable from 0, to the last
element (1 less than array’s size). To access elements
inside age array of size 4, we will use following loop.
for (int i=0;i<4; i++) or for (int i=0; i<=3; i++)
Engr. SDJK, CSE, MUET Jamshoro 25
Program
#include <iostream>
using namespace std;
int main(){
int age[4]; //array 'age' of 4 ints
for(int j=0; j<4; j++) //get 4 ages
{
cout << "Enter an age number "<<j+1<<‘\n’;
cin >> age[j]; //access array element
}
for(int j=0; j<4; j++) //display 4 ages
cout << "You entered " << age[j] << endl;
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 26
Explanation
We have used two for loops, one for input of the
elements, while other is for output of the same elements
on the screen.
As our Array’s size is 4, so our loop starts from 0 and
ends up with 3 (less than 4).
As j’s scope is only to first loop, we also can use same
name for counter variable inside second loop, so we have
to declare it once again.
Engr. SDJK, CSE, MUET Jamshoro 27
Averaging the array elements #include <iostream>
using namespace std;
int main(){
const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 variables
cout << "Enter widget sales for 6 days\n";
for(int j=0; j<SIZE; j++)cin >> sales[j];
double total = 0;
for(int j=0; j<SIZE; j++) total += sales[j];
double average = total / SIZE; // find average
cout << "Average = " << average << endl;
return 0;
} Engr. SDJK, CSE, MUET Jamshoro 28
Initializing Arrays: An alternative
int days_per_month[12]=
{31,28,31,30,31,30,31,31,30,31,30,31};
Now first element days_per_month [0] will contain 31 and
next will contain 28 and so on, so last element
days_per_month [11] will contain 31.
Similarly,
Engr. SDJK, CSE, MUET Jamshoro 29
Multidimensional Arrays
Can be two dimensional array, three dimensional, and so
on.
Working with more than two dimensions is really hard
and time consuming.
A two dimensional array is like a two dimensional matrix.
So, a two dimensional array is an array of arrays.
const int DISTRICTS = 4;
const int MONTHS = 3;
double sales[DISTRICTS][MONTHS];
Engr. SDJK, CSE, MUET Jamshoro 30
For every sales array, there would be 4 arrays, each array
capable of storing 3 elements.
To access we would use two for loops:
for(int i=0;i<DISTRICTS;i++){
for(int j=0;j<MONTHS;j++){
cin>>sales[i][j];
}
Engr. SDJK, CSE, MUET Jamshoro 31
An Alternative Initialization
int sales[2][3]={ {1, 1, 4}, {5, 7, 80} };
Engr. SDJK, CSE, MUET Jamshoro 32
Two – Dimensional Array in Memory
Two for loops
(nested)
Can be used to
Access both
dimensions
Engr. SDJK, CSE, MUET Jamshoro 33
Adding two 3x3 Matrices
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int matrixA[3][3];
int matrixB[3][3];
int result [3][3];
int i,j;
//continued
Engr. SDJK, CSE, MUET Jamshoro 34
//Enter Matrix A
for(i=0;i<3;i++){
for(j=0;j<3;j++){
cout<<"Enter Matrix A Element number:row
"<<i<<" Column "<<j<<"\n“;cin>>matrixA[i][j];
}
}
//Enter Matrix B
for(i=0;i<3;i++){
for(j=0;j<3;j++){
cout<<"Enter Matrix B Element number:row
"<<i<<" Column "<<j<<"\n";cin>>matrixB[i][j];
}
}
Engr. SDJK, CSE, MUET Jamshoro 35
//Calculate the sum in new Matrix in
show its elements on the screen
for(i=0;i<3;i++){
for(j=0;j<3;j++){
result[i][j]=matrixA[i][j]+matrixB[
i][j];
}
}
cout<<"*********************************
*****\n";
Engr. SDJK, CSE, MUET Jamshoro 36
cout<<"Here is the Result below\n\n\n\n";
for(i=0;i<3;i++){
for(j=0;j<3;j++){
cout<<setw(5)<<result[i][j]<<setw(10)<<
" ";
}
cout<<endl;
}
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 37
Addresses and Pointers
Every Byte in a computer memory has an address
assigned to it.
So, data is stored at different locations (bytes) of different
sequential addresses inside memory.
Addresses (in computing) are simply numbers (Mostly in
hexadecimal format).
When your program loads inside memory, it is assigned a
address or range of addresses inside RAM (memory).
Which means variables at functions start at some
particular address inside memory.
Engr. SDJK, CSE, MUET Jamshoro 38
Addresses inside Memory
If var1 is int
2 Bytes
If var2 is char
1 Byte
If var3 is float
4 Bytes
Engr. SDJK, CSE, MUET Jamshoro 39
The Address-of (&) Operator
Used to retrieve or fetch or find the address of a variable
inside memory.
(&) Ampersand sign is used in front of variable to find it’s
address.
Addresses can be printed used
cout<<&variable-name; //statement.
Engr. SDJK, CSE, MUET Jamshoro 40
Program (Address-of operator)
#include <iostream>
using namespace std;
int main()
{
int var1 = 11; //define and initialize
int var2 = 22; //three variables
int var3 = 33;
cout << &var1 << endl << &var2 << endl<<
&var3 << endl;
return 0;
}
Engr. SDJK, CSE, MUET Jamshoro 41
Pictorial Explanation
Addresses appear in descending
Order.
Below is the sample output.
Engr. SDJK, CSE, MUET Jamshoro 42
Pointers
Pointers are special type of variables to hold the addresses of variables inside memory.
A pointer variable has special format of definition.
We can-not store address in other variables than pointers.
Like
int a, b;
a=&b; //invalid, because address of b can’t be stored inside a, which is not a pointer variable.
So, Pointers are distinguished from conventional variables by use of Asterik (*) in front of the data-type or variable-name.
Engr. SDJK, CSE, MUET Jamshoro 43
Declaring Pointers
The * sign shows that ptr is a pointer variable, which can
hold the address of an integer data-type variable.
Or in other words, ptr is a pointer to integer variable.
Other data-types can be used as following:
And so on.
Engr. SDJK, CSE, MUET Jamshoro 44
Program
Engr. SDJK, CSE, MUET Jamshoro 45
#include <iostream>
using namespace std;
int main()
{
int var1 = 11; //two integer variables
int var2 = 22;
cout << &var1 << endl << &var2 << endl << endl;
int* ptr; //pointer to integers
ptr = &var1; //pointer points to var1
cout << ptr << endl; //print pointer value
ptr = &var2; //pointer points to var2
cout << ptr << endl; //print pointer value
return 0;
}
Explanation
Engr. SDJK, CSE, MUET Jamshoro 46
ptr is a pointer variable, which now holds the address on
var1, both ptr and var1 have int data type.
Here is the sample output:
The End
Engr. SDJK, CSE, MUET Jamshoro 47
Test#3
Engr. SDJK, CSE, MUET Jamshoro 48
On 21 April, 2012, Saturday.
Assignment
Engr. SDJK, CSE, MUET Jamshoro 49
Q#1. What is Data Processing; discuss the applications of computers in civil engineering. Discuss contributions of Charles Babbage?
Q#2. Convert following numbers from binary to decimal (i-ii-v) and from decimal to binary (iii-iv) respectively.
i) (100100111)2 ii) (101100011)2 iii) (4500)10
iv) (101100101)10 v) (10111010)2
Q#3: What is the output of the following lines of code?
1) int a = 5, b=2;
float z = a/b;
cout<<z;
II) What is the output the following lines of code?
bool condition1;
condition = 7/2>1;
cout<<condition;
Assignment cont.
Engr. SDJK, CSE, MUET Jamshoro 50
Q#4. What is operator’s precedence? Discuss in detail.
Elaborate using the Tabular explanation.
Q#5. What is BIOS and POST? Discuss in detail.
Q#6: Survey computer market and find out, what is
specifications of most selling computer along with
peripherals. Model numbers, and different detailed
specifications along with input, output, storage devices.