14 views

Uploaded by Wassen Hejjawi

computer programming

- CCP All Papers Till Jun 2012 (2010 Scheme)
- SAS-IML Users Guide
- Advanced_Excel_Formulas.xls
- Advanced-Excel-Formulas-xls.xls
- Oats
- Computer Science board paper
- Matlab Codes for Method of Characteristics
- Computer programming c++ solved labs
- Fortran
- BendTechV1.1 En
- AB%20Logix5000%20Controllers%20User%20Manual
- CSE (CP MANUAL)
- The NumPy Array_ a Structure for Efficient Numerical Computation
- rr320504-language-processors
- R Prague Lesson 1
- A Little Book of r for Time Series
- 13667_15860_Compiler (Statement of Problem) (1)
- Php
- 4 Array and Matrix Operations.pdf
- finalreview

You are on page 1of 6

College of Engineering

Dept. of Computer Science & Engineering

Computer Programming

GENG106

Lab Handbook

Fall 2012 Semester

Lab 9: Arrays

Objectives

At the end of this lab, you should be able to

Use arrays in C++.

Pass arrays to functions.

Use arrays with files.

Use 2-dimensional arrays.

Quick Review

An array is a group of consecutive memory locations that are related by the fact that they all have

the same name and same type, e.g. double stress[3]; declares a 1-dimensional array of size

3, i.e. the number of elements is 3.

A subscript (sometimes called index) is used to refer to a particular location within the array, e.g.

stress[0], stress[1], etc.

To pass an array to a function, the name of the array is passed, e.g. x=max(stress);

By default arrays are passed to functions using pass-by-reference, e.g. sort(stress);

A 2-dimensional array represents a table of values consisting of information arranged in rows

and columns, e.g. double nodeStress[100][3];

To access a particular element, two subscripts are specified. The first subscript references the

row and the second references the column, e.g. nodeStress[53][1].

#include <iostream>

using namespace std;

int main()

{

int diameter[] = {20,22,19,23,20,21,23,25,19};

for(int x = 0; x < 9; x++)

cout <<"Diameter["<< x <<"] = " << diameter[x]<<endl;

return 0;

}

a)

_______________________________________________________________________________

_______________________________________________________________________________

b)

c)

d)

e)

f)

What is the subscript (index) of the last element of diameter? _____________________

Change the condition of the for-loop to become x<=9 and run the program. What is the

last line of the output? ______________________ Is it correct? ___________________

Change the condition of the for-loop back to x<9 and save your program.

Now, add to your program statements to calculate and output the sum of the diameters

and the average diameter.

#include <iostream>

using namespace std;

void replace(int x[],int s, int oldValue, int newValue )

{

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

if(x[i]==oldValue)

x[i]=newValue;

}

int main()

{

int a[5]={2,7,4,2,8};

cout<<"Array before calling function replace \n";

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

cout<<a[i]<< '\t';

cout<<endl;

replace (a, 5, 2, 9);

cout<<"Array after calling function replace \n";

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

cout<<a[i]<< '\t';

cout<<endl;

return 0;

}

_____________________________

_____________________________

_____________________________

_____________________________

From the example above, we can say that array is passed to a function by _______________.

Assume you have an array called force that has 10 elements and we want to pass that array to

a funtion called sort. Which one of the following is a correct function call:

a) sort(force);

b) sort(force[]);

c) sort(force[10]);

Overload the replace function by providing an implementation that replaces all the

elements in the array x[]of size s, with a value val. Use the following prototype:

replace(int x[], int s, int val);

3) Write a C++ program that reads 10 real numbers into an array called distance, and then

calculates and prints the sum of positive numbers sumPositive, and the sum of negative numbers

sumNegative.

Index number

0

4.2

-6.3

9.4

-12

-4.1

-2

1

9.2

Sample output

a) A column vector x of size n is usually represented, in C++, by a 1-dimensional array. Adding

two vectors x and y then reduces to adding the corresponding elements x[0]+y[0], x[1]+y[1],

etc.

Write a C++ function called addVectors() that has four parameters: three integer arrays x, y

and z and their size, n. Let your function store the sum of x and y in the array z.

Write a driver program to test your function using the following data:

and b

Sample output

b) The norm of a vector x, written as x, is a measure of its size (a scalar quantity). One of the

simple vector norms is the Euclidean norm, defined as x =

.

Add to your program of Question (4a) a function called norm2() that takes as parameters an

integer array, x, and its size, n. Let the function return the double value representing the

Euclidean norm of x.

Add to your program statements to print the norms of the vectors

Sample output

and

given above.

5) a) Write a C++ program that initializes an array called diameters with the following numbers,

and then stores the numbers into a file named result.dat:

16.25, 18.96, 22.34, 18.94, 17.42, 22.63.

b) Write another C++ program to read the numbers in the result.dat file created in Question-5a

and display the data. Additionally, your program should compute and display the sum and average

of the data.

NOTE: Review the use of files in Lab5 Exercises 4 through 8.

6) The following program initializes the 2-dimensional array marks[][]that represents a table of

marks of five students in three subjects: math, computer and English. Compile and run the program.

#include <iostream>

#include<iomanip>

using namespace std;

int main()

{

double marks[][3]={

{89,88,90},

{80,85,79},

{96,92,95},

{68,73,55},

{45,60,58}

};

cout<<"Stud# Math Computer English\n";

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

{

cout<<setw(3)<<i+1;

for(int j=0;j<3;j++)

cout<<setw(8)<<fixed<<setprecision(1)<<marks[i][j];

cout<<endl;

}

return 0;

}

_______________________________________________________________________

_______________________________________________________________________

_______________________________________________________________________

The following function returns the average of the elements of a double array x of size n:

double average(double x[], int n)

{

double sum=0;

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

sum+=x[i];

return sum/n;

}

Add the above function to your program and then use it to output the average mark for each

student as shown in the typical output below. (Hint: the ith row of our array is marks[i]; a 1dimensional array of size 3).

3

Typical Output:

The following function returns the letter grade corresponding to a given mark:

char grade(double mark)

{

if(mark>=90)

return 'A';

else if (mark>=80)

return 'B';

else if (mark>=70)

return 'C';

else if (mark>=60)

return 'D';

else

return 'F';

}

Add the above function to your program and then use it to produce a table of the student

numbers and the corresponding letter grade for each of the three subjects, as well as for the

average grade.

Typical Output:

7) The norm of a

parameter, and number of columns is fixed to be 3), the function finds the Frobenius norm of the

matrix represented by the array a.

{

double sum=0;

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

for(int j=0;j<3;j++)

{

aij=a[i][j];

sum+=aij*aij;

}

return sqrt(sum);

}

True or false: when we pass a 2-dimensional array to a function, the number of columns

should be constant.

Use the function above, to output the Frobenius norm of the marks array of Question (5).

Ans=303.814

8) Transposing a matrix is swapping rows and columns, for example the matrix

is transposed into

Write C++ program that reads a 2-dimensional array (3 rows, 3 columns), and then transposes this

array. Then display the array after transposing.

I/O Sample (user input is marked in red):

Enter row-1: 1 2 4

Enter row-2: 3 6 7

Enter row-3: 9 5 8

The transpose of the above matrix is:

1 3 9

2 6 5

4 7 8

Press any key to continue . . .

9) Specify whether each of the following C++ array declarations is correct () or wrong ():

____ int a[];

____

int a[3];

____

int a[5]={3,4};

____

int a[3]={0};

- CCP All Papers Till Jun 2012 (2010 Scheme)Uploaded byRoshan Sridhar
- SAS-IML Users GuideUploaded byillinimtw
- Advanced_Excel_Formulas.xlsUploaded byJust Basic
- Advanced-Excel-Formulas-xls.xlsUploaded byballagabi
- OatsUploaded byapareek3
- Computer Science board paperUploaded bymangikashifraza
- Matlab Codes for Method of CharacteristicsUploaded byaeroacademic
- Computer programming c++ solved labsUploaded bySheharyar Awan
- FortranUploaded byAdrian Tec
- BendTechV1.1 EnUploaded byafonsomoutinho
- AB%20Logix5000%20Controllers%20User%20ManualUploaded byJavier Flores
- CSE (CP MANUAL)Uploaded byprasad1237
- The NumPy Array_ a Structure for Efficient Numerical ComputationUploaded byDaniel Camarena Perez
- rr320504-language-processorsUploaded bySRINIVASA RAO GANTA
- R Prague Lesson 1Uploaded byErwin Bakker
- A Little Book of r for Time SeriesUploaded byNeelanjan Biswas
- 13667_15860_Compiler (Statement of Problem) (1)Uploaded byDrishti Chhabra
- PhpUploaded byshinde_jayesh2005
- 4 Array and Matrix Operations.pdfUploaded byAugusto De La Cruz Camayo
- finalreviewUploaded bycrutili
- Lab_1Uploaded byĐức Huy
- Part15-SoftwareInterruptsUploaded byMafuzal Hoque
- VectorsUploaded bya.vidyanand
- Efficient Algorithms for Array RedistributionUploaded byDevender Bindal
- 06_ArraysAndStringsUploaded byLedon Michelle
- Tut 8Uploaded byapi-3817778
- Qb Computer ScUploaded byganeshkumar_smmkg
- Con1855_chambille-Operating a 16tb JvmUploaded bysbabuind
- Lecture 4 Data Structure QueueUploaded bySello Hlabeli
- Additional QuestionsUploaded byAynaa Eis

- Shaikh Ahmad Bin Ali AlThaniUploaded byWassen Hejjawi
- Wastes in Class - InterviewsUploaded byWassen Hejjawi
- Wastes in Class - InterviewsUploaded byWassen Hejjawi
- About at RiskUploaded byWassen Hejjawi
- hr annaUploaded byWassen Hejjawi
- Krajewski 9thUploaded bySubrata Halder
- Student Workload GuidelinesUploaded byWassen Hejjawi
- Question 3 Business HwUploaded byWassen Hejjawi
- Productio Operations Planning_aggregate Planning - Chapter3Uploaded byAlessandro Nájeraa
- min x11Uploaded byWassen Hejjawi
- business hw.docxUploaded byWassen Hejjawi
- Question 1 business hw.docxUploaded byWassen Hejjawi
- Sample Mid1Uploaded byWassen Hejjawi
- (Layout)Uploaded byWassen Hejjawi
- Question 1 business hw.docxUploaded byWassen Hejjawi
- Comments on WebsiteUploaded byWassen Hejjawi
- TER201E_2011-12_F_midterm2_soltnUploaded byWassen Hejjawi
- Numerical Methods Lab 3Uploaded byWassen Hejjawi
- CENG 106 Lab6.pdfUploaded byWassen Hejjawi
- CENG 106 Lab7Uploaded byWassen Hejjawi
- TP1 FormulationUploaded byWassen Hejjawi
- CENG 106 Lab8Uploaded byWassen Hejjawi
- ch07_01Uploaded byWassen Hejjawi
- SQC-Lab1Uploaded byWassen Hejjawi
- Formulation lp 3423Uploaded bymazin903
- notes7Uploaded byAbhishek Sarkar
- Chap 8Uploaded byNikhil Dedhia
- Linear ProgrammingUploaded byMandy Chen

- Ls-dyna Manual Vol i r7.0Uploaded bymauretta1234
- Introduction to seismic inversion methodsUploaded byJefferson
- M2016-Scientific Computing With MATLAB-Paul Gribble-Math Eng Chap01 g Chap02Uploaded byhieuhuech
- LTE SIB and Layer3 Messages in DetailUploaded byManish Chaturvedi
- book review about BloomartUploaded byPalke
- analysis of matthais pintscherUploaded byMichael Alexander
- Tbox-RTUUploaded byNic Ric
- Collins Practice Tests for YLE Flyers Teacher s GuideUploaded byMolly Hicks
- sql-server-maintenance-plans-brad-ebook.pdfUploaded bytracdiadk52
- Computer Information SystemUploaded byfarwah
- lesson plan 4-readings and slamUploaded byapi-435193908
- Sap NotesUploaded byJonathan McHill
- How to Create a Macro in WordUploaded byPretty Miloue
- RPH BI T4 2019Uploaded byIkhwan Mutaza
- CmdUploaded byWubie Nega
- IE_403_LAB_1Uploaded byAldo Ruiz
- Mapbasic v7.0 User GuideUploaded byPakar Baca
- Brain Injury & Social Perception Deficits -- Research Article (8 Pages)Uploaded byGeneric_Persona
- PuzzleProgram.py.txtUploaded byJeremy Burke
- Comprehensive Articulatory PhoneticsUploaded bycasperdetello
- Solution setUploaded byqwerty12311
- Crsp Mfdb GuideUploaded byJoseph
- Alphacool PCO3 Controls ManualUploaded byttt449
- The Evaluation of HSC Syllabus in the Context of BangladeshUploaded byShafiq Roneiy
- The Use of Group Investigatio1Uploaded bydiana
- The Origin of Europe with the Greek Discovery of the WorldUploaded byRemmert Ouweltjes
- Morrowind Scripting for Dummies 8Uploaded byMiroslav Mojic
- Steven Pinker's Language Instinct TheoryUploaded byAlex Leonard
- The Joys of Being CatholicUploaded byDik Sajona
- Jazz Piano LessonsUploaded byAnonymous FDfNDMadU