You are on page 1of 50

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

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.
3 Engr. SDJK, CSE, MUET Jamshoro

Structures Definition

Accessing a Structure variables:


4 Engr. SDJK, CSE, MUET Jamshoro

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

Structures in memory

Engr. SDJK, CSE, MUET Jamshoro

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

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; }
8 Engr. SDJK, CSE, MUET Jamshoro

Output

Engr. SDJK, CSE, MUET Jamshoro

Structure
All Structures have their own variables

10

Engr. SDJK, CSE, MUET Jamshoro

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 };
11 Engr. SDJK, CSE, MUET Jamshoro

//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; }
12 Engr. SDJK, CSE, MUET Jamshoro

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
13 Engr. SDJK, CSE, MUET Jamshoro

Program (Prototyping/Declaration of the function)

// functiondemo1.cpp // demonstrates simple function #include <iostream> using namespace std; void starline(); //function declaration // (prototype)

14

Engr. SDJK, CSE, MUET Jamshoro

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; }
15 Engr. SDJK, CSE, MUET Jamshoro

Program (Function Definition)


// starline() // function definition void starline() //function declarator { for(int j=0; j<20; j++) //function body cout << '*'; cout << endl; }

16

Engr. SDJK, CSE, MUET Jamshoro

Explanation

The program consists of two functions: main() and starline().Youve 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.

17

Engr. SDJK, CSE, MUET Jamshoro

The Function Declaration


Also called function prototyping. Just as you cant use the variable, before you declare it, Simply you also cant 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.
18 Engr. SDJK, CSE, MUET Jamshoro

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.
19 Engr. SDJK, CSE, MUET Jamshoro

Summary of the Function Components

20

Engr. SDJK, CSE, MUET Jamshoro

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; }
21 Engr. SDJK, CSE, MUET Jamshoro

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.
22 Engr. SDJK, CSE, MUET Jamshoro

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 arrays size i.e. 3 = 4-1.

23

Engr. SDJK, CSE, MUET Jamshoro

Arrays inside the memory

Arrays 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.

24

Engr. SDJK, CSE, MUET Jamshoro

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 arrays 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++)

25

Engr. SDJK, CSE, MUET Jamshoro

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; }
26 Engr. SDJK, CSE, MUET Jamshoro

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 Arrays size is 4, so our loop starts from 0 and ends up with 3 (less than 4). As js 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.

27

Engr. SDJK, CSE, MUET Jamshoro

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; }
28 Engr. SDJK, CSE, MUET Jamshoro

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,

29

Engr. SDJK, CSE, MUET Jamshoro

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

30

Engr. SDJK, CSE, MUET Jamshoro

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

31

Engr. SDJK, CSE, MUET Jamshoro

An Alternative Initialization

int sales[2][3]={ {1, 1, 4}, {5, 7, 80} };

32

Engr. SDJK, CSE, MUET Jamshoro

Two Dimensional Array in Memory


Two for loops (nested) Can be used to Access both dimensions

33

Engr. SDJK, CSE, MUET Jamshoro

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
34 Engr. SDJK, CSE, MUET Jamshoro

//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]; } }
35 Engr. SDJK, CSE, MUET Jamshoro

//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";
36 Engr. SDJK, CSE, MUET Jamshoro

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; }
37 Engr. SDJK, CSE, MUET Jamshoro

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.

38

Engr. SDJK, CSE, MUET Jamshoro

Addresses inside Memory

If var1 is int

2 Bytes 1 Byte

If var2 is char

If var3 is float

4 Bytes

39

Engr. SDJK, CSE, MUET Jamshoro

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 its address. Addresses can be printed used cout<<&variable-name; //statement.

40

Engr. SDJK, CSE, MUET Jamshoro

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; }
41 Engr. SDJK, CSE, MUET Jamshoro

Pictorial Explanation
Addresses appear in descending Order.

Below is the sample output.

42

Engr. SDJK, CSE, MUET Jamshoro

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 cant 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 variablename.
43 Engr. SDJK, CSE, MUET Jamshoro

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.

44

Engr. SDJK, CSE, MUET Jamshoro

Program
#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; }
45 Engr. SDJK, CSE, MUET Jamshoro

Explanation

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:

46

Engr. SDJK, CSE, MUET Jamshoro

The End

47

Engr. SDJK, CSE, MUET Jamshoro

Test#3

On 21 April, 2012, Saturday.

48

Engr. SDJK, CSE, MUET Jamshoro

Assignment
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;
49 Engr. SDJK, CSE, MUET Jamshoro

Assignment cont.

Q#4. What is operators 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.

50

Engr. SDJK, CSE, MUET Jamshoro