Array Manipulation-Introduction To Programming-Lecture Notes, Study notes of Computer Programming

A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: Array, Manipulation, Real, Problem, Design, Recipe, Stored, Process, Loop, Iterative, Structure, Element, Index, Structure, Matrix

Typology: Study notes

2011/2012

Uploaded on 08/06/2012

anchal
anchal 🇮🇳

4.6

(9)

95 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture No. 13
Reading Material
Deitel & Deitel – C++ How to Program Chapter 4
4.5, 4.9
Summary
Array Manipulation
Real World Problem and Design Recipe
Exercises
Array Manipulation
We have already discussed what an array is. Identical or similar values are stored in
related to the context of the problem
f an individual is a number. We don't
in one array as, in contextual terms, they are different things.
ight of individuals will be stored in one
ay and the age in some other one. The idea behind the array is that whenever you
is the easiest way and what are the
ng in terms of loops. We pick up the first element of the array and process it.
bers, we should try to understand it in terms of a matrix.
atrices in mathematics have rows and column and there is always a number at each
w and column intersection. Suppose we have a matrix of dimension 3 * 3 i.e. a
simple two-dimensional array. We want to input some numbers to that array first.
After reading these numbers, we want to output them in such a fashion that the last
an array. The identical and similar terms here are
we try to solve. For example, height or age o
store height and age
These can not be mixed in one array. So the he
arr
have similar data with multiple values, it is easier and more elegant to store them in
an array.
Let's try to find out, how to process arrays. What
issues related to this process.
As discussed in previous lectures, whenever we come across an array, we start
thinki
Then the second array element is processed and so on. Naturally that falls into an
iterative structure.
Let's try to understand how to process a two dimensional array. The following
example can help us comprehend it effectively.
Suppose we have a two-dimensional array of numbers. While dealing with a two-
dimensional array of num
M
ro
124
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Array Manipulation-Introduction To Programming-Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!

Lecture No. 13

Reading Material

Deitel & Deitel – C++ How to Program Chapter 4 4.5, 4.

Summary

Array Manipulation Real World Problem and Design Recipe Exercises

Array Manipulation

We have already discussed what an array is. Identical or similar values are stored in related to the context of the problem f an individual is a number. We don't in one array as, in contextual terms, they are different things. ight of individuals will be stored in one ay and the age in some other one. The idea behind the array is that whenever you

is the easiest way and what are the

ng in terms of loops. We pick up the first element of the array and process it.

bers, we should try to understand it in terms of a matrix. atrices in mathematics have rows and column and there is always a number at each w and column intersection. Suppose we have a matrix of dimension 3 * 3 i.e. a simple two-dimensional array. We want to input some numbers to that array first. After reading these numbers, we want to output them in such a fashion that the last

an array. The identical and similar terms here are we try to solve. For example, height or age o store height and age These can not be mixed in one array. So the he arr have similar data with multiple values, it is easier and more elegant to store them in an array.

Let's try to find out, how to process arrays. What issues related to this process.

As discussed in previous lectures, whenever we come across an array, we start thinki Then the second array element is processed and so on. Naturally that falls into an iterative structure.

Let's try to understand how to process a two dimensional array. The following example can help us comprehend it effectively. Suppose we have a two-dimensional array of numbers. While dealing with a two- dimensional array of num M ro

docsity.com

row is printed first, followed by second last and so on till the first row that is printed at the bottom. We don't want to change the column numbers with this output. It is not a difficult task. As it is a two-dimensional array so there is a row subscript and a column subscript. Following example will make the matter further clear. Suppose we have the following array: int a[3][3];

We will access elements of it as: a[row index][column index] e.g. a[1][2]. This is a single element at row 1 and column 2 of array a.

The flow chart to read in numbers into the two-dimensional array is given on the next page. See the code snippet below:

const int maxRows = 3; const int maxCols = 3; int row, col;

int a[maxRows][maxCols];

// To input numbers in the array for (row = 0; row < maxRows; row ++) { for(col=0; col < maxCols; col ++) { cout << "\n" << "Enter " << row << "," << col << "element: "; cin >> a[row][col];

} }

Now let's see what this nested loop structure is doing. The outer loop takes the first row i.e. row 0, then instantly inner loop begins which reads col 0, 1 and 2 elements of the row 0 into the array. Afterwards, control goes back to the outer loop. The row counter is incremented and becomes 1 i.e. row 1 or second row is taken for processing. Again, the inner loop reads all the elements of second row into the array. This process goes on until all the elements for three rows and three columns array are read and stored in the array called a.

docsity.com

reverse the rows of the matrix (flip the matrix) and display it. There several ways of doing it. You might have already started thinking of how can we ix and copy the array elements into this x while flipping the elements at the same time. But we should keep in mind the ent. The problem statement is 'to read the array elements and then imply oes not state anything about storing the lements inside the memory.

lease e flow chart to display the flipped matrix on the next page.

ally, we start our loops from zero and keep incrementing the counter until a ertain bigger value is attained. But this is not mandatory. We can start from a bigger mber and keep on decrementing the counter every time. To display the rows in everse order, we can start from the last row and go to the first row by decrementing rogramming trick. However, we have to e care of the value of the index. r code inside nested loops for flipping the elements as under-

<< '\n' << "The flipped matrix is: " << '\n';

a [row][col] << '\t'; } cout << '\n';

Note the '\t' character in the above code. It is a tab character that displays tab (spaces) at the cursor position on the screen. Similary '\n' as told in previous lectures is newline character which takes the cursor to the new line.

It is better to print the original matrix elements before showing the flipped matrix elements so that you can really see whether your function has flipped the matrix or not.

To run this function for the big-sized arrays, adjust the values of the maxRows and maxCols constants as the rest of the program remains the same..

Whenever we work with arrays, normally the loops are there. If the array is single dimensional, there will be one loop. A two-dimensional arrays is going to have pair of nested loops and so on.

Now we want to are flip the matrix. We may declare a new matr matri problem statem s display it in the reverse row order'. It d e

P see th

Norm c nu r the row counter every time. It is very simple p tak We can write ou

// To flip the elements of the matrix cout

for ( row = maxRows-1; row >= 0; row --) { for ( col = 0; col < maxCols; col + { cout <<

docsity.com

No

Row Order

maxRows = n maxCols = n a[maxRows][maxCol

while row >= 0

Yes

No

col = 0

while

col < maxCols

][col]

Yes

Print a[row

col++

row--

Input the array ‘a’ elements

row = maxRows - 1

Exit

Exit

docsity.com

playFlippedMatrix(int a[][maxCols])

for (row = maxRows - 1; row >= 0; row --)

for(col = 0; col < maxCols; col ++) { ow][col] << '\t'; }

}

int row, col;

for (row = 0; row < maxRows; row ++) {

for(col = 0; col < maxCols; col ++) { cout << a[row][col] << '\t'; } cout << '\n'; }

}

void dis { int row, col;

cout << a[r

cout << '\n';

docsity.com

ly solved very simple problems to understand processing of ys. You can t t your capability of doing so through an exercise by inputting ading in) a matrix and print it in re column order. Here, the rows remain the ame.

al problem derstand the concept of Trans ose of a Matrix. Transpose of a matrix means that ange rows and columns, the first row becomes the first column, nd row becomes the second column and so on. Mathematically, the transpose can

) should be replaced with A(j,i) wh d column indexes.

or thi ose, we take a square matrix (a matrix with equal number of rows and olumn ight. L t's say he arr s ‘arraySize’. Please see the flow chart ge.

e wr d loops:

temp; or (row = 0; row < arraySize; row ++)

0; col < arraySize; col ++) { re using the swapping mechanism temp = a[row][col]; // Save the original value in the temp variable [row][col] = a[col][row]; t the original value

e interchanging values, we should be careful. We can't simply write: a[row][col] a[col][row]. We will lose information this way. We need a swapping mechanism re to interchange the elements properly.

solved. You are strongly recommended to ite this program and run it to see the problem area.

ng interesting that we are interchanging the value of first row, first hen we are doing transpose of a matrix, iagonal elements will remain unchanged as the row and column indexes are the e. Then we interchange the row 0, col 1 element with row 1, col 0. The row 0, col hen we process second row i.e. row he 1, col 0 will be swapped with row 0, col 1 but these are the same elements, at ents swapped once are swapped again to their original positions if the loops are .

Till now, we have on arra es (re verse s

Let's move on to slightly more practic. Before going ahead, we need to un p when we interch seco be written as: A(i,j ere i and j are row an

F s purp c s) to transpose. Here, if you are thinking in terms of loops, you are absolutely r e t ay is 'a', with dimension a for this problem on the next pa

W ite a pair of neste

int f {

for (col =

// Interchange the values he

a a[col][row] = temp; //Take ou

} }

Whil

he

We have yet to do more to get the problem wr

It is somethi column with itself, which means nothing. W the d sam 2 element with row 2, col 0. What will happen w

  1. T row already swapped in the above iteration. Therefore, this is the problem area th elem run in all the rows and columns. As a result, the resultant matrix remains unchanged

docsity.com

nally. We will get two triangles i.e.

oking at a triangle, let's say upper triangle, we can see that all

e before

e. w i.e.

be

(two- l array), displays its contents, transposes it and then displays the transposed matrix.

matrix cout << "\n\n" << "The transposed matrix is: " << '\n';

Then what is the solution of the problem? Now draw a matrix on the paper and cut it diago upper triangle and lower triangle. We only need to interchange one triangle with the other and not the whole of the matrix. Now the question is, how we can determine the limits of triangles? By lo the rows are being processed as the triangle crosses every row. Similarly all the columns are being processed because the first row in the upper triangle covers all th columns. The only difference is that we will not process the beginning element starting each row. That means that we will not start the inner loop (columns loop) with index 0. Rather we start with the current row number. Therefore, for first row i. row 0, we will process from row 0, col 0 to row 0, col arraySize-1. For second ro row 1, we will process from row 1, col 1 to row 1, col arraySize-1 while in case of third row i.e. row 2, we will go from row 2, col 2 to row 2 , col arraySize-1. If you structure the loops in this manner, the correct behavior of matrix transposition will found.

The full source code to solve this problem by taking the upper triangle and swapping it with the lower triangle is given below:

/* Array Manipulation - Transpose of a Square Matrix: This program reads a matrix dimensiona */

#include

const int arraySize = 3;

void readMatrix(int arr[][arraySize]); void displayMatrix(int a[][arraySize]); void transposeMatrix(int a[][arraySize]);

void main(void) {

int a[arraySize][arraySize];

// Read the matrix elements into the array readMatrix(a);

// Display the matrix cout << "\n\n" << "The original matrix is: " << '\n'; displayMatrix(a);

//Transpose the matrix transposeMatrix(a);

//Display the transposed

docsity.com

displayMatrix(a);

}

ow << ", " << col << " element: ";

for (col = row; col < arraySize; col ++)

/* Interchange the values here using the swapping mechanism */

e the original value in the temp variable a[row][col] = a[col][row];

void readMatrix(int arr[][arraySize]) { int row, col;

for (row = 0; row < arraySize; row ++ { for(col=0; col < arraySize; col ++) { cout << "\n" << "Enter " << r cin >> arr[row][col];

} cout << '\n'; } }

void displayMatrix(int a[][arraySize]) { int row, col;

for (row = 0; row < arraySize; row ++) {

for(col = 0; col < arraySize; col ++) { cout << a[row][col] << '\t'; } cout << '\n'; }

}

void transposeMatrix(int a[][arraySize]) { int row, col; int temp; for (row = 0; row < arraySize; row ++) {

temp = a[row][col]; // Sav

docsity.com

or all esign recipe.

etimes, the

is charged on that amount, which is deducted every month. But if

s getting Rs. 20,000 per m The interesting situation develops if there an anomaly in the tax rates i.e. a person who is getting higher salary takes home

design recipe, let's see what steps we need to follow.

uter language

ine what are the inputs of this program. What data should ram. We will also try to determine if there are some constants or manipulation. We list down all the constants. Then we split

precise problem

ine those employees less take-home salary than others with lower initial income."

w states that: ersons with salaries ranging from Rs. 0 to Rs. 5,000 per duction rate is 0%. the persons with salaries ranging from Rs. 5, month.

Real Word Problem and Design Recipe

We will take one problem that is not very complex but will follow it rigorously f steps of d

Inpractical life, the employees get salaries and pay taxes honestly. Som process of drawing salaries and payment of taxes may lead to some interesting situation. Suppose, a person draws salary of Rs. 10,000 per month. A certain percentage of tax the sala y of th r e person is more than Rs. 10,000 per month, then the tax rate is different. Similarly if a person i onth, he/she would be charged more under a different tax rate slab. is lesser money as compared to the other person with less gross salary.

To further elaborate it, we suppose that there is company 'C' where 100 or less than 100 persons are employed. The salaries of the employees and their tax rates are known to us. We are required to list those unlucky persons, who are getting lesser take-home salary (net salary) than their colleagues with less gross salaries but lower tax rates.

As per our

A design recipe asks us to analyze the problem first and write it in a precise statement that what actual the problem is. Also by formulating the precise statement, we need to provide some examples to illustrate. At the design phase, we try to break up the problem into functional units and resort to a detailed designing. Then we move to implementation stage where the pseudo code is translated into the comp and then the program is compiled and run to ensure that it works as expected.

At the first step i.e Analysis, we try to have a precise problem statement. Once it is established, we try to determ be provided to this prog required for calculation it up into functions and modules.

Let's try to make a precise statement of the above problem. The statement is:

"Given tax brackets and given employees gross salaries, determ who actually get

Suppose the tax deduction la No tax will be deducted for p month or in other words tax de 5% tax deductionwill be made from to Rs. 10,000 per

docsity.com

uction ed. h salaries ranging from Rs. 20,001 and higher, 15% tax deduction ld be made.

ulate the problem.

s per rules, 10,000 is 500 rupees. So the take

. 9500. the unfortunate individual, whose gross salary is Rs, 10,001 falls in the next ve to pay tax worth Rs 1000.1. That means the lesser than the person with he problem. can calculate the net salaries of all individuals, determining all the unlucky ones. . For looking into the input the salaries of these people. stated in the problem, the number of employees of the company 'C is at most 100. o we know the size of the array. But for some other company, suppose company 'D', e don't know the number of employees. Therefore, it makes sense to take input from e have determined the number of ployees, we will input the gross salary of each of employees. But where will we

will store the gross salary. Our program after calculating the net

ind the ithms. At the higher level design, we assume that there would be a y to determine the unlucky individuals. Finally, a list of unlucky employees would e prepared. For that, we will simply output the employee numbers. rements of this problem. As earlier ntioned, we will use a two dimensional array to store the gross and net salaries and

take a single dimensional array of 'int' type. We will initialize the ore, by default, all re lucky. Whenever, we will find an unlucky individual by using the two imensional array for that individual. So the program.

ce guidelines are the same e. be p and try to explain what is required from the user. When the program runs him/her. So there would be prompts in the e input data will be coming from d displayed on the screen. This is a rudimentary interface analysis.

istributed the program into four major parts:

ion of unlucky individuals and

For persons with salaries ranging from Rs. 10,001 to Rs. 20,000, a 10% tax ded rate would be employ For persons wit wou

Taking these rules, let's form

Consider the example of a person with a salary of Rs. 10,000 per month. A he/she would be charged by 5% of tax rate. 5% of home salary of the person is Rs Now bracket of tax rate of 10%. He will ha take home salary of this person is Rs. 9000.9, which is lower gross salary of Rs. 10,000. This is t We

Now we will carry out the analysis of the requirements requirements, we have to see, how to As S w the user for the number of employees. Once w em store the gross salary? For this purpose, we will use the two-dimensional array. In the first column, we salary for each employee will write (store) it in the second column of the array. At the next stage, we will f out the unlucky individuals. This will be based on analysis of algor wa b We want to workout the space and storage requi me output the list of unlucky employees. That means we need a storage to store that list. For this, we will array with zero. '0' means the individual is lucky. Theref individuals a dimensional array, we will write '1' in single d this is the storage requirement of

Afterwards, we will discuss the interface issues. The interfa i. olite the user will know what is required from program where the user will key in the data. All th keyboard an

We have d Input Salary calculation Identificat Output

docsity.com

ble by reference using the '&' sign to this function. This will ensure that whatever user inputs inside this function getInput(), will be available in the main function. here is another way that we get input from the user inside the main function and then are going to do the same in our nction.

put(double sal[][2], int numEmps);

for (int i = 0; i < numEmps; i ++) //Note that this numEmps is local to this

{ cin >> sal[i][0]; // Get the gross salary for each employee }

e tax, we will write a function. This function will be passed in similar arameters as getInput function to calculate the taxes for all the employees. There is ce. ten d are available inside main function. The 'numEmps' variable on e other hand is passed by value to getInput() function. Therefore, any changes done main

condition. The function to calculate net lary also has interesting issues which will be explained in the next lecture.

Here is the source code of the first cut solution for real world problem:

  • This is the first cut of the program to solve the real world problem of 'Unlucky Employees' */

#include

void getInput(double sal[][2], int numEmps); void calcNetSal(double sal[][2], int numEmps); void findUnluckies(double sal[][2], int numEmps, int lucky[]); void markIfUnlucky(double sal[][2], int numEmps, int lucky[], int upperBound, int empNbr); void printUnluckies(int lucky[], int numEmps);

void main(void) { const int arraySize=100; double sal[arraySize][2]; int lucky[arraySize] = {0}; int numEmps;

/* Read the actual number of employees in the company */

varia the T pass this by value to the getInput() function. We fu

getIn {

function

To calculat p one important point to reiterate here i.e. by default, arrays are passed by referen That means if getInput() function puts some values in the 'sal' array, these are writ in the 'sal' array an th by geInput() function will not affect the original value of 'numEmps' inside the function.

We will continue with this problem to determine algorithm that what is the precise sequence of steps to determine the unlucky employees. For this, we need to analyze a bit more because it contains a complex 'if' sa

docsity.com

cout << "\n Please enter the total number of employees in your company: "; ps;

/* Read the gross salaries of the employees into the array 'sal' */ getInput(sal, numEmps);

aries of the employees and store them in the array */ ies .. ";

/* Find the unlucky employees */ cout << "\n\n Locating the unlucky employees ... "; findUnluckies(sal, numEmps, lucky);

/* Print the unlucky employee numbers */ \n Printing the unlucky employees ... "; kies(lucky, numEmps); }

void ge ut( { for (int i = 0; i < numEmps; i++) //Note that this numEmps is local to this function { ss salary for employee no." << i << ": "; in >> sal[i][0]; // Store the gross salary for each employee

ction

al[i][0] >= 0 && sal[i][0] <= 5000) {

cin >> numEm cout << '\n';

/* Calculate net sal cout << "\n\n Calculating the net salar. calcNetSal(sal, numEmps);

cout << "\n printUnluc

tInp double sal[][2], int numEmps)

cout << "\n Please enter the gro c } }

void calcNetSal(double sal[][2], int numEmps) { for (int i = 0; i < numEmps; i++) //Note that this numEmps is local to this fun { if(s

/* There is no tax deduction / sal[i][1] = sal[i][0]; } else if(sal[i][0] >= 5001 && sal[i][0] <= 10000) { / Tax deduction is 5% / sal[i][1] = sal[i][0] - (.05 * sal[i][0]); } else if (sal[i][0] >= 10001 && sal[i][0] <= 20000) { / Tax deduction is 10% */ sal[i][1] = sal[i][0] - (.10 * sal[i][0]); } else if (sal[i][0] >= 20001)

docsity.com

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

cout <<"\n Employee No.: " << i; }

void printUnluckies(int lucky[], int numEmps) {

{ if(lucky[i] == 1) {

Exercises

Suppose you have a Square matrix of order 5 * 5. Draw flow chart and write a program to input (read in) a matrix and print it in reverse column order, the rows main the same.

r triangle and swap it with upper triangle.

n Identity matrix is a square matrix whose diagonal elements are '1' and remaining

re

Suppose you have a Square matrix of order 5 * 5. Draw flow chart and write a program to transpose the matrix, take lowe

A elements are '0'. Suppose you are given a square matrix of size n * n. Write a program to determine if this is an Identity matrix.

docsity.com