CS007A Fall 12 Second Midterm

Size: px
Start display at page:

Download "CS007A Fall 12 Second Midterm"

Transcription

1 CS007A Fall 12 Second Midterm 1. A programmer writes the following code to create a 3x2 matrix and print it out. a. Are there syntax errors? List all that you can find. b. Suppose the syntax errors are fixed. Are there run-time errors? List all that you can find. #include <iostream> using namespace std; int main() int coordinates[2][2] = 0,2,3,1,4,5; output(coordinates[][2]); void output(int coordinates) for(i = 0; i < 3; ++i) for(j = 0; j < 3; --j) cout << coordinates[j][i] << " "; cout << endl; 2. Consider following complete program: #include <iostream> using namespace std; const int arraysize = 4; void show2darray(int [][arraysize],int); int main() int a[arraysize][arraysize] = 0; for(int i=0;i<arraysize;++i) a[i][i] = i*i; show2darray(a,arraysize); return 0; void show2darray(int b[][arraysize],int n) for(int i=0;i<n;++i) for(int j=0;j<n;++j) cout << b[i][j] << " "; cout << endl; a. What is the function prototype here and what is it for? b. How many bytes are allocated in memory for array a? Hint: use the sizeof operator. c. In the function, show2darray(), which variable is passed by reference and which variable is passed by value? d. How would the program be altered to produce the output below?

2 3. Consider the following complete program. #include <iostream> using namespace std; const int dim = 3; void outerprod(double [], double [], double [][dim], int); int main() double prod[dim][dim] = 0; double fact01[] = 1.,2.,3.; double fact02[] = 4.,5.,6.; outerprod(fact01, fact02, prod, dim); outerprod(fact02, fact01, prod, dim); return 0; void outerprod(double f1[], double f2[], double p[][dim], int dim) for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) p[i][j] = f1[i]*f2[j]; a. How many bytes are allocated in memory for prod? b. Why does dim have to be a const? c. Which variables are passed by reference in outerprod()? d. Fill in a table of values for i, j and p[i][j] corresponding to each of the function calls to outerprod(). That is, thread through the program, step by step, showing the values for i, j and p[i][j] at each step. 4. Write a program to simulate 128 rolls of two 6-sided dice and store the results in a 2x128 double-indexed array named Dice. Then write a function called Eights which takes this array and returns the number times the sum of the dice is 8. In the main() function, use cout << Eights(Dice) to print this result to the console. Use the const qualifier where appropriate. The program should be complete and run without bugs when typed in and compiled. 5. Suppose that p = 0x0012FF50, &a = 0x0012FF44, &p = 0x0012FF38. What will be output by the following code? int main() int a[] = 22, 33, 44, 55, 66, 77, 88, 99 ; int* p = &a[3]; // p points to a[3] cout << "p = " << p << ", *p = " << *p; cout << "\n&a = " << &a; // ok: a is an lvalue cout << "\n&p = " << &p; // ok: p is an lvalue cout << "\n&(a[5]) = " << &(a[5]); // ok: a[5] is an lvalue cout << "\n&(*(a+5)) = " << &(*(a+5));// ok: *(a+5) is an lvalue cout << "\n&(*(p+2)) = " << &(*(p+2));// ok: *(p+2) is an lvalue cout << "\n&(p+2) = " << p+2; //&(p+2); // ERROR: p+2 is not an lvalue cout << endl;

3 6. Consider the code below. a. How many syntax errors can you find? b. Are there any logic errors? c. Are there any parameters that should be qualified as const? d. Fix the program so it works and write a couple of sentences describing what the program is intended to do. #include <iostream> #include <iomanip> using namespace std; void mean(int [], int ); void median( int [], int ); void mode( int [], int [], int ); void bubblesort( int[], int ); void printarray(int[], int ); int main() const int responsesize = 99; // size of array responses int frequency[ 10 ] = 1 ; // initialize array frequency // initialize array responses int response[ ] = 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7 ; // process responses mean( response, responsesize ); median( response, responsesize ); mode( frequency, response, responsesize ); return 0; // indicates successful termination // end main // calculate average of all response values void mean(int answer[], int arraysize ) int total = 0; cout << "********\n Mean\n********\n"; // total response values for ( int i = 0; i < arraysize; i++ ) total += answer[ i ]; // format and output results cout << fixed << setprecision( 4 ); cout << "The mean is the average value of the data\n" << "items. The mean is equal to the total of\n" << "all the data items divided by the number\n" << "of data items (" << arraysize << "). The mean value for\nthis run is: " << total << " / " << arraysize << " = " << static_cast< double >( total ) / arraysize << "\n\n"; // end function mean

4 // sort array and determine median element's value void median( int answer[], int size ) cout << "\n********\n Median\n********\n" << "The unsorted array of responses is"; printarray( answer, size ); // output unsorted array bubblesort( answer, size ); // sort array cout << "\n\nthe sorted array is"; printarray( answer, size ); // output sorted array // display median element cout << "\n\nthe median is element " << size / 2 << " of\nthe sorted " << size << " element array.\nfor this run the median is " << answer[ size / 2 ] << "\n\n"; // end function median // determine most frequent response void mode( int freq[], int answer[], int size ) int largest = 0; // represents largest frequency int modevalue = 0; // represents most frequent response cout << "\n********\n Mode\n********\n"; // initialize frequencies to 0 for ( int i = 1; i <= 9; i++ ) freq[ i ] = 0; // summarize frequencies for ( int j = 0; j < size; j++ ) ++freq[ answer[ j ] ]; // output headers for result columns cout << "Response" << setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << " \n" << setw( 56 ) << " \n\n"; // output results for ( int rating = 1; rating <= 9; rating++ ) cout << setw( 8 ) << rating << setw( 11 ) << freq[ rating ] << " "; // keep track of mode value and largest fequency value if ( freq[ rating ] > largest ) largest = freq[ rating ]; modevalue = rating; // end if // output histogram bar representing frequency value for ( int k = 1; k <= freq[ rating ]; k++ ) cout << '*'; cout << '\n'; // begin new line of output // end outer for // display the mode value cout << "The mode is the most frequent value.\n" << "For this run the mode is " << modevalue << " which occurred " << largest << " times." << endl; // end function mode // function that sorts an array with bubble sort algorithm void bubblesort( int a[], int size ) int hold; // temporary location used to swap elements // loop to control number of passes for ( int pass = 1; pass < size; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < size ; j++ ) // swap elements if out of order if ( a[ j ] > a[ j + 1 ] ) hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold;

5 // end if // end function bubblesort // output array contents (20 values per row) void printarray( const int a[], int size ) for ( i = 0; i < size; i++ ) if ( i % 20 == 0 ) // begin new line every 20 values cout << endl; cout << setw( 2 ) << a[ i ]; // end for // end function printarray 7. Consider the following code for manipulating polynomials (below). a. Get the program working in your compiler and use it to analyze the roots for i ii. 1 Describe your results. b. Make a flow chart to describe the operation of the i. findupperbound() ii. findzero(). iii. descartesrulepos() iv. findallzeros() // G Hagopian // Polynomial function handler #include < iostream> using namespace std; const int N = 100; // maximim size of the polynomial coeff array void getcoeff(double [], const int, int & degree); void clearcoeff(double c[]); // zero out coefficients double dodivision(double dividend[], double quotient[], int degree, double input, bool show); //double f(double [], int, double); void printpoly(double [], int degree); double findupperbound(double [], int degree); double findlowerbound(double [], int degree); int descartesrulepos(double [], int degree); int descartesruleneg(double [], int degree); double findzero(double [], double & left, double right, int degree,bool up); void findallzeros(double [], double [], double left, double right, int degree); void getmenu(double coeff[],double quotient[], double roots[], int & degree); double abs(double x) return x>0? x : -x; int main() int degree = 4; double coeff[n] = 1,-10,35,-50,24; // The coefficient of x^n is coeff[n] double quotient[n] = 0; double roots[n] = 0;// An array to hold the roots while(1) getmenu(coeff,quotient,roots,degree); return 0; void getmenu(double coeff[],double quotient[], double roots[], int & degree)

6 double r, start = 0, max = 1000, min; int choice, k; // i for choice 9. cout << "Choose what you want to do: " << endl << "1: Print the current polynomial." << endl << "2: Enter a new polynomial." << endl << "3: Do synthetic division by x - c." << endl << "4: Evaluate the polynomial at a point." << endl << "5: Find lower and upper bounds on the zeros." << endl << "6: List the possible number(s) of positive and negative roots using D's rule of signs." << endl << "7: Find a positive zero above a given number, if there is one." << endl << "8: Find a negative zero below a given number, if there is one." << endl << "9: Find all real zeros of a polynomial." << endl; do // get choice //cin.clear(); cin.ignore(); cout << "\nchoice: "; cin >> choice; while(choice < 1 choice > 9); switch (choice) case 1 : cout << "\nhere's your polynomial: "; printpoly(coeff,degree); cout << endl << endl; cin.ignore(); cin.get(); break; case 2 : getcoeff(coeff, N, degree); cout << "\nyou entered\n"; printpoly(coeff, degree); cout << endl << endl; cin.ignore(); cin.get(); break; case 3 : cout << "\nenter a value of c, and we'll divide f(x) by x-c: "; cin >> r; cout << "\nthe value of f(" << r << ") is " << dodivision(coeff,quotient,degree,r,true) << endl << endl; cin.ignore(); cin.get(); break; case 4 : cout << "\nenter a value of c, and we'll evaluate f(c): " ; cin >> r; cout << "\nthe value of f(" << r << ") is " << dodivision(coeff,quotient,degree,r,false) << endl << endl; cin.ignore(); cin.get(); break; case 5 : cout << "\nthe zeros of the polynomial are between x = "; cout << findlowerbound(coeff, degree); cout << " and x = "; cout << findupperbound(coeff, degree) << endl << endl; cin.ignore(); cin.get(); break; case 6 : cout << "\nthe possible numbers of positive zeros is "; for(int i = descartesrulepos(coeff, degree); i >= 0; i -= 2) cout << i << " "; cout << "\nthe possible numbers of negative zeros is ";

7 for(int i = descartesruleneg(coeff, degree); i >= 0; i -= 2) cout << i << " "; cin.ignore(); cin.get(); break; case 7 : max = findupperbound(coeff,degree); do cout << "\nenter the left endpoint of an interval where you seek a positive zero: "; cin >> start; while (start > max); cout << "\nthere is a postive zero near where x = "; cout << findzero(coeff,start,max,degree,true); cout << endl << endl; cin.ignore(); cin.get(); break; case 8 : max = findlowerbound(coeff,degree); do cout << "\nenter the right endpoint of an interval where you seek a negative zero: "; cin >> start; while (start < max); cout << "\nthere is a negative zero near where x = "; cout << findzero(coeff,start,max,degree,false); cout << endl << endl; cin.ignore(); cin.get(); break; case 9 : for(int j = 0; j < N; j++) roots[j]=0; // clear roots array min = findlowerbound(coeff, degree); max = findupperbound(coeff, degree); findallzeros(coeff,roots,min,max,degree); cout << "\nthe roots are "; k = 0; while(roots[k]!=0 && roots[k++]<10e99) cout << roots[k-1] << " "; cin.ignore(); cin.get(); break; default : break; void clearcoeff(double c[]) for(int i = 0; i < N; ++i) c[i]=0; void getcoeff(double c[], const int N, int & degree) do cout << "\nenter the degree of the polynomial, " << "\na number less than " << N << " : "; cin >> degree; while (degree >= N); for(int i = 0; i <= degree; ++i) cout << "\nenter the coefficient of x^" << i << ": "; cin >> c[i];

8 double dodivision(double dividend[], double quotient[], int degree, double r, bool show) clearcoeff(quotient); quotient[degree-1] = dividend[degree]; double value = dividend[degree]; for(int i = degree; i > 1; i--) value *= r; value += dividend[i-1]; quotient[i-2] = value; value *= r; value += dividend[0]; if(show) cout << "\nthe result of Polynomial division is \n\n"; printpoly(dividend,degree); if(r>=0) cout << endl << " = (x - " << r << ")*("; else cout << endl << " = (x + " << -r << ")*("; printpoly(quotient,degree-1); cout << ")"; if(value!=0) if(value>0) cout << " + " << value; else cout << " - " << -value; cout << endl; return value; void printpoly(double c[], int degree) if (degree <= 1) if(degree == 1) // it's a linear polynomial if(c[1]==1) cout << "x"; else cout << c[1] << "*x"; c[0] > 0? cout << " + " << c[0] : cout << " - " << -c[0]; else cout << c[0]; // it's a constant else // degree>1 // First print the leading term if(c[degree] == 1) cout << "x^" << degree; // treat the cases where leading coeff is 1 separately else if(c[degree] == -1) cout << "-x^" << degree; else // leading coeff is not 1 or -1 cout << c[degree]<< "x^" << degree; // Print out the rest of the terms for(int i = degree-1; i>1; i--) if(c[i]>0) if(c[i]==1) cout << " + x^" << i; //don't print coeff 1 else cout << " + " << c[i] << "*x^" << i; if(c[i]<0) if(c[i]==-1) cout << " - x^" << i; // don't print coeff -1 else cout << " - " << -c[i]<< "*x^" << i;

9 if((degree-i+1)%10 == 0) cout << endl; if(c[1] > 0) cout << " + " << c[1] << "*x"; if(c[1] < 0) cout << " - " << -c[1]<< "*x"; if(c[0] > 0) cout << " + " << c[0]; if(c[0] < 0) cout << " - " << -c[0]; double findupperbound(double c[], int degree) bool found = false; double quot[n] = 0; double incrmnt = 1/(2*c[degree]), remainder; double x = 0., sign; int count = degree-1; //, parity=0; while(!found) // && diff>bound/1000) remainder = dodivision(c, quot, degree, x,false); sign = quot[count]>0? 1. : -1.; count = degree-1; while(sign*quot[count-1]>=0 && count > 0) --count; if(count==0 && sign*remainder>=0) return x; else x += incrmnt; //cout << "\nx = " << x; return 0; cout << endl << endl; double findlowerbound(double c[], int degree) bool found = false; double sign; double quot[n] = 0; //This is an attempt to scale the increment proportional to the //leading coefficient double decrmnt = 1/(2*c[degree]), remainder; double x = 0.; int count = degree-1;//, parity=0; while(!found) // this conditional can likely be refined remainder = dodivision(c, quot, degree, x, false); //evaluate but don't show results sign = quot[count] < 0? -1. : 1.; // since count is initialized to 1 less than degree, it's the // degree of quot if(degree > 2) while(quot[count-1]*sign<=0 && quot[count]*quot[count-2]>=0 && count > 1) --count; if(count==1 && remainder*quot[0]<=0) return x; else x -= decrmnt; else if(quot[1]*remainder >=0 && quot[1]*quot[0] <=0)

10 return x; else x -= decrmnt; return 0; cout << endl << endl; int descartesrulepos(double c[], int degree) int count = 0; for(int i = 0; i < degree; ++i) if(c[i]*c[i+1] <= 0) ++count; return count; int descartesruleneg(double c[], int degree) int count = 0; for(int i = 0; i < degree; ++i) if(c[i]*c[i+1] >= 0) ++count; return count; // findzero takes a polynomial (coefficient array), an initial x value, a // bound, and the degree // bool up is used to tell whether to search up the x-axis or back // to the right. double findzero(double c[], double & x, double max, int degree, bool up) if(max == 0) return 10e100; // max is an upper/lower bound on the roots. If max = 0, none. double q[n]=0, step; // if(up) step = 1/(10*c[degree]); // for searching through positives else step = -1/(10*c[degree]); // for searching through negatives double x_next = x+step, y = dodivision(c,q,degree,x,false); double y_next = dodivision(c,q,degree,x_next,false); double midx, midy, toler=1.e-10; // First walk through some smallish x increments to find a change of // signs: while (y*y_next>0 && abs(x_next) < abs(max)) // y has not changed signs & not beyond bound y = y_next; x_next += step; // if not up, incr is negative y_next = dodivision(c,q,degree,x_next,false); if(y_next == 0) x = x_next; // set reference variable return x; // Got lucky! if(abs(x_next) > abs(max)) x = x_next; return 10e100; x = x_next;

11 x_next -= step; y = y_next; y_next = dodivision(c,q,degree,x_next,false); midy = y_next; while(abs(midy)>1e-10) midx = (x+x_next)/2; midy = dodivision(c,q,degree,midx,false); if(midy*y<0) // root is on the left side x_next = midx; else x = midx; if(up && x_next<=max) x = x_next; return x_next; else if(!up && x_next>=max) x = x_next; return x_next; else return 10e100; void findallzeros(double c[], double roots[], double negmax, double posmax, int degree) double step = 1/(2*c[degree]); // Fairly large step size scaled to leading coefficient double x = step; // start looking in positive direction int i=0; while(x<posmax) // posmax is determined by findupperbound() roots[i++] = findzero(c,x,posmax,degree,true); x += step; x = -step; // start looking in negative direction while(x>negmax) //negmax is determined by findlowerbound() roots[i++] = findzero(c,x,negmax,degree,false); cout << "\nroots[" << i-1 << "] = " << roots[i-1]; x -= step;

12 CS007A Second Midterm Solutions 1. A programmer writes the following code to create a 3x2 matrix and print it out. a. Are there syntax errors? List all that you can find. b. Suppose the syntax errors are fixed. Are there run-time errors? List all that you can find. #include <iostream> using namespace std; int main() int coordinates[2][2] = 0,2,3,1,4,5; output(coordinates[][2]); void output(int coordinates) for(i = 0; i < 3; ++i) for(j = 0; j < 3; --j) cout << coordinates[j][i] << " "; cout << endl; SOLN: There are these syntax errors. (1) Either a prototype for output() should be given, or the definition should precede main(). void output(int [][2]); would be a good prototype. (2) int coordinates[2][2] = 0,2,3,1,4,5; Here coordinates should be initialized with dimensions, [3][2]. (3) The call to output() in main() should contain only the name of the array, output(coordinates), not the dimensions. (4) The definition of output() should include the dimensions of the array at least the second size should be specified: (5) There are a bunch of run-time errors and syntax errors in the body of the definition of output(). The integer counters for the for loops are not declared, and the column index should only count two, instead of three. Here s one way to fix this function definition: void output(int [][2]); int main() int coordinates[3][2] = 0,2,3,1,4,5; output(coordinates); void output(int coordinates[][2]) for(int i = 0; i < 3; ++i) for(int j = 0; j < 2; ++j) cout << coordinates[i][j] << " "; cout << endl;

13 2. Consider following complete program: #include <iostream> using namespace std; const int arraysize = 4; void show2darray(int [][arraysize],int); int main() int a[arraysize][arraysize] = 0; for(int i=0;i<arraysize;++i) a[i][i] = i*i; show2darray(a,arraysize); return 0; void show2darray(int b[][arraysize],int n) for(int i=0;i<n;++i) for(int j=0;j<n;++j) cout << b[i][j] << " "; cout << endl; a. What is the function prototype here and what is it for? SOLN: The prototype is void show2darray(int [][arraysize],int); and is used to declare there is a function by that name and to specify its formal parameter list and what sort of return value it has (none, in this case.) b. How many bytes are allocated in memory for array a? Hint: use the sizeof operator. SOLN: The array a requires 4 bytes for each of its 16 integers for a total of 64 bytes. c. In the function, show2darray(), which variable is passed by reference and which variable is passed by value? SOLN: Array a (or b, as it is renamed in the body of the definition) is passed by reference (implicitly, since it s the name of an array) and arraysize (renamed n by the function definition) is passed by value. d. How would the program be altered to produce the output below? SOLN: You d change arraysize from 4 to 5. Then add a nested for loop in the main() function like so: const int arraysize = 5; int main() int a[arraysize][arraysize] = 0; for(int i=0;i<arraysize;++i) for(int j = 0; j < arraysize; ++j) a[i][j] = (i+1)*(j+1); show2darray(a,arraysize); cout << endl << sizeof(a); return 0;

14 3. Consider the following complete program. #include <iostream> using namespace std; const int dim = 3; void outerprod(double [], double [], double [][dim], int); int main() double prod[dim][dim] = 0; double fact01[] = 1.,2.,3.; double fact02[] = 4.,5.,6.; outerprod(fact01, fact02, prod, dim); outerprod(fact02, fact01, prod, dim); return 0; void outerprod(double f1[], double f2[], double p[][dim], int dim) for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) p[i][j] = f1[i]*f2[j]; a. How many bytes are allocated in memory for prod? SOLN: Since const int dim = 3 and each int is 4 bytes, the 3*3=9 ints require 9*4 = 36 bytes. b. Why does dim have to be a const? SOLN: Because it s used to allocate memory for an array, which must be of constant size. c. Which variables are passed by reference in outerprod()? SOLN: Only dim is not passed by reference, double f1[], double f2[], double p[][dim] are arrays and, as such, are implicitly passed by reference. d. Fill in a table of values for i, j and p[i][j] corresponding to each of the function calls to outerprod(). That is, thread through the program, step by step, showing the values for i, j and p[i][j] at each step. i j p i j p

15 4. Write a program to simulate 128 rolls of two 6-sided dice and store the results in a 2x128 double-indexed array named Dice. Then write a function called Eights which takes this array and returns the number times the sum of the dice is 8. In the main() function, use cout << Eights(Dice) to print this result to the console. Use the const qualifier where appropriate. The program should be complete and run without bugs when typed in and compiled. SOLN: #include <iostream> #include <cstdlib> // rand() #include <ctime> //srand(time()) using namespace std; int Eights(int Dice[2][128]) int cntr = 0; for(int i = 0; i<128; ++i) if(dice[0][i]+dice[1][i]==8) ++cntr; return cntr; int main() srand(unsigned(time(0))); int Dice[2][128]; for(int i = 0; i<128; ++i) Dice[0][i] = 1+rand()%6; Dice[1][i] = 1+rand()%6; cout << Eights(Dice) << endl; 5. Suppose that p = 0x0012FF50, &a = 0x0012FF44, &p = 0x0012FF38. What will be output by the following code? int main() int a[] = 22, 33, 44, 55, 66, 77, 88, 99 ; int* p = &a[3]; // p points to a[3] cout << "p = " << p << ", *p = " << *p; cout << "\n&a = " << &a; // ok: a is an lvalue cout << "\n&p = " << &p; // ok: p is an lvalue cout << "\n&(a[5]) = " << &(a[5]); // ok: a[5] is an lvalue cout << "\n&(*(a+5)) = " << &(*(a+5));// ok: *(a+5) is an lvalue cout << "\n&(*(p+2)) = " << &(*(p+2));// ok: *(p+2) is an lvalue cout << "\n&(p+2) = " << p+2; //&(p+2); // ERROR: p+2 is not an lvalue cout << endl; SOLN: Clearly, the statement int* p = &a[3]; assigns the address of the 4 th element of the array a to the pointer, p. The dereferencing operator, when applied to point p, the produces the value stored at that address, which is the fourth element of the array a[3] = 55. So the first cout produces: p = 0x0012FF50, *p = 55

16 The second cout shows the address of a, so cout << "\n&a = " << &a; produces: &a = 0x0012FF44 The 3 rd cout tells us the address of the pointer itself, so cout << "\n&p = " << &p; produces: &p = 0x0012FF38 The 4 th cout tells the address of the 6 th element of the array, and since each element is a int requiring 4 bytes, this is 8 bytes beyond a[3], so cout << "\n&(a[5]) = " << &(a[5]); produces: &(a[5]) = 0x0012FF58 The 5 th cout prints the address of the contents at the address which is 5 ints beyond a (note the & and * essentially just cancel each other out) so that cout << "\n&(*(a+5)) = " << &(*(a+5)); produces 20 bytes (0x14) more than a, or the same thing as above: &(*(a+5)) = 0x0012FF58 The 6 th is two ints beyond where p started, which is, again, the address of a[5]. So we d get &(*(p+2)) = 0x0012FF58 Similarly, the address of a[5] can be obtained by p+2; So cout << "\n&(p+2) = " << p+2; also produces &(p+2) = 0x0012FF58 but the left side of this equation is misleading, since pointer arithmetic doesn t work with address of the pointer itself! Trying to print out &(p+2) will lead to a syntax error. 6. Consider the code [above #6]. a. How many syntax errors can you find? b. Are there any logic errors? c. Are there any parameters that should be qualified as const? d. Fix the program so it works and write a couple of sentences describing what the program is intended to do. SOLN: There is a syntax error in printarray(). The for loop index i has not been initialized. This is easily remedied like so: void printarray( const int a[], int size ) for (int i = 0; i < size; i++ ) //and so on. Attempting to compile the code after correcting this minor error leads to the cryptic linker error, error LNK2019: unresolved external symbol "void cdecl printarray(int * const,int)" (?printarray@@yaxqahh@z) referenced in function "void cdecl median(int * const,int)", which appears to reference some parameter list involving constant pointers to integers. A careful inspection of the code reveals the prototype: void printarray(int[], int ) which doesn t comport with this formal parameter list in the definition: printarray(const int a[], int size). Changing the prototype to match the definition, the code compiles, but there is a run-time error after

17 producing this much output: ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = ******** Median ******** The unsorted array of responses is The sorted array is The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** It appears the sorted array is a bit out of whack. Analyzing the bubblesort() function we see that it has some serious logic errors, which we can rebuild like so: void bubblesort( int a[], int size ) int hold; // temporary location used to swap elements // loop to control number of passes for(int pass = 1; pass < size; pass++) // loop to control number of comparisons per pass for ( int j = 1; j <= size-pass ; j++ ) // swap elements if out of order if ( a[ j-1 ] > a[ j ] ) hold = a[ j-1 ]; a[ j-1 ] = a[ j ]; a[ j ] = hold; // end if // end function bubblesort

18 After running the program with bubblesort() fixed, we get this output, which appears to be correct: ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = ******** Median ******** The unsorted array of responses is The sorted array is The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** Response Frequency Histogram * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value.

19 For this run the mode is 8 which occurred 27 times. Press any key to continue Consider the following code for manipulating polynomials ([above]). a. Get the program working in your compiler and use it to analyze the roots for i ii. 1 Describe your results. b. Make a flow chart to describe the operation of the i. findupperbound() ii. findzero(). iii. descartesrulepos() iv. findallzeros() SOLN (a i) Running the program and choosing (2) from the menu to enter the polynomial and then (9) to find all zeros, we get the following: Choose what you want to do: 1: Print the current polynomial. 2: Enter a new polynomial. 3: Do synthetic division by x - c. 4: Evaluate the polynomial at a point. 5: Find lower and upper bounds on the zeros. 6: List the possible number(s) of positive and negative roots using D's rule of signs. 7: Find a positive zero above a given number, if there is one. 8: Find a negative zero below a given number, if there is one. 9: Find all real zeros of a polynomial. choice: 2 Enter the degree of the polynomial, a number less than 100 : 4 Enter the coefficient of x^0: 27 Enter the coefficient of x^1: -45 Enter the coefficient of x^2: -120 Enter the coefficient of x^3: 20 Enter the coefficient of x^4: 48 You entered 48x^4 + 20*x^3-120*x^2-45*x + 27 Choose what you want to do: 1: Print the current polynomial. 2: Enter a new polynomial. 3: Do synthetic division by x - c. 4: Evaluate the polynomial at a point. 5: Find lower and upper bounds on the zeros.

20 6: List the possible number(s) of positive and negative roots using D's rule of signs. 7: Find a positive zero above a given number, if there is one. 8: Find a negative zero below a given number, if there is one. 9: Find all real zeros of a polynomial. choice: 9 roots[3] = roots[4] = -1.5 roots[5] = 1e+101 The roots are Hmmm.evidently, some debugging is in order. To make it a bit easier to analyze , hard-wire it as the default polynomial in main(): double coeff[n] = 27,-45,-120,20,48; Then, since puts the 1e+101 capstone at the end of the list of roots, insert --i; //back up a notch to account for findzero's capstone between the two while loops in findallzeros() to be sure that this value is overwritten between the positive and negative zeros. The code now works and we see that Choose what you want to do: 1: Print the current polynomial. 2: Enter a new polynomial. 3: Do synthetic division by x - c. 4: Evaluate the polynomial at a point. 5: Find lower and upper bounds on the zeros. 6: List the possible number(s) of positive and negative roots using D's rule of signs. 7: Find a positive zero above a given number, if there is one. 8: Find a negative zero below a given number, if there is one. 9: Find all real zeros of a polynomial. choice: 9 roots[0] = roots[1] = -1.5 roots[2] = 1e+101 roots[2] = roots[3] = 1.5 roots[4] = 1e+101 The roots are So For part (ii) first use a calculator to compute the floating point approximations for the coefficients: , , , 0.5 and so on, so we can hardwire the polynomial with double coeff[n] = 1,0,-0.5,0, e-2,0, e- 3,0, e-5; Now running the program causes it to hang. Why? We

21 must debug! And, when in doubt...cout! Inseting these lines into the while loop of findzero() we that the initial x values are way too far out! choice: 9 x = y = e+029 x = y = e+030 A little reflection helps us realize that if the leading coefficient (1/40320) is very small, then the value of x will be too large (in absolute value) so we go in and alter the code in findzero() to read if(up) step = 1e-1;//1/(10*c[degree]); // for searching through positives else step = -1e-1;//(10*c[degree]); // for searching through negatives Then we see these values: choice: 9 x_next = -0.1 y = 1 x_next = -0.2 y = x_next = -0.3 y = [.. and so on..] x_next = -1.4 y = x_next = -1.5 y = roots[0] = roots[1] = x_next = y = e-011 x_next = y = x_next = y = x_next = y = [.. and so on.. ] x_next = y = x_next = y = x_next = y = roots[2] = x_next = y = e-010 x_next = y = [.. and so on.. ] x_next = y = e+011 x_next = y = e+011 A couple of anomalies here: (1) For some reason, is assigned to be a root twice, and (2) it doesn t find an upper bound where it should this is confirmed by inserting the code cout << "\nmax = " << max; into the findzero() function and viewing the result: max = (which is actually a min..). Max and min bounds on the roots are computed in the switch 9 section: case 9 : for(int j = 0; j < N; j++) roots[j]=0; // clear roots array min = findlowerbound(coeff, degree); max = findupperbound(coeff, degree); findallzeros(coeff,roots,min,max,degree); cout << "\nthe roots are "; k = 0; while(roots[k]<1e99) //roots[k]!=0 && cout << roots[k] << " "; ++k; cin.ignore(); cin.get(); break;

22 Which are apparently not being correctly computed perhaps because of the zero coefficients in polynomial? Perhaps. It s a debugging opportunity for you! The actual roots are approximately (according to the TI-85) and as shown in the (Maple V) graph shown below: The flow charts for part (b) follow. Note that

23

24 Here s findzero(). Could use some work too And descartesrulepos():

25

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved. Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

CS 007A Midterm 1 Practice Chapters 1 5

CS 007A Midterm 1 Practice Chapters 1 5 CS 007A Midterm 1 Practice Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: b. Determine the

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

Chapter Four: Loops II

Chapter Four: Loops II Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers and Strings. Adhi Harmoko S, M.Komp Pointers and Strings Adhi Harmoko S, M.Komp Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable Declarations and

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional

More information

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 Arrays Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 6 - Arrays 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays

More information

BITG 1113: Array (Part 1) LECTURE 8

BITG 1113: Array (Part 1) LECTURE 8 BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in

More information

PIC 10A. Review for Midterm I

PIC 10A. Review for Midterm I PIC 10A Review for Midterm I Midterm I Friday, May 1, 2.00-2.50pm. Try to show up 5 min early so we can start on time. Exam will cover all material up to and including todays lecture. (Only topics that

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Elements of C in C++ data types if else statement for loops. random numbers rolling a die Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011 The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

More information

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No. The American University in Cairo Computer Science & Engineering Department CSCE 106 Instructor: Final Exam Fall 2010 Last Name :... ID:... First Name:... Section No.: EXAMINATION INSTRUCTIONS * Do not

More information

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays 4 Examples Using Arrays 5 Passing Arrays to Functions 6 Sorting Arrays 7 Case Study: Computing Mean, Median and Mode Using Arrays 8 Searching Arrays

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1 ELEC 330 1 Structured Programming Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne Algorithm Development Conditional Expressions Selection Statements Loops 206_C3

More information

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

More information

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

Computer Programming Lecture 14 Arrays (Part 2)

Computer Programming Lecture 14 Arrays (Part 2) Computer Programming Lecture 14 Arrays (Part 2) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr 1 Topics The relationship between

More information

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7] Arrays Arrays deal with storage of data, which can be processed later. Arrays are a series of elements (variables) of the same type placed consecutively in memory that can be individually referenced by

More information

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

CS 103 Lecture 3 Slides

CS 103 Lecture 3 Slides 1 CS 103 Lecture 3 Slides Control Structures Mark Redekopp 2 Announcements Lab 2 Due Friday HW 2 Due next Thursday 3 Review Write a program to ask the user to enter two integers representing hours then

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

pointers + memory double x; string a; int x; main overhead int y; main overhead

pointers + memory double x; string a; int x; main overhead int y; main overhead pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

Problem Solving: Storyboards for User Interaction

Problem Solving: Storyboards for User Interaction Topic 6 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:

More information

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1 Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures

More information

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below: QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the

More information

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

REVIEW. The C++ Programming Language. CS 151 Review #2

REVIEW. The C++ Programming Language. CS 151 Review #2 REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold Arrays 1. Introduction An array is a consecutive group of memory locations that all have the same name and the same type. A specific element in an array is accessed by an index. The lowest address corresponds

More information

LAB: WHILE LOOPS IN C++

LAB: WHILE LOOPS IN C++ LAB: WHILE LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 2 Introduction This lab will provide students with an introduction

More information

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using const with Pointers Selection Sort Using Pass-by-Reference 2

More information

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver) Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80 Exam 2 CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson Question Points Score 1 18 2 29 3 18 4 15 Total: 80 I understand that this exam is closed book and closed note and

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A. Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011 The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Final Exam Fall 2011 Last Name :... ID:... First Name:... Section No.: EXAMINATION

More information

Chapter 6 - Pointers

Chapter 6 - Pointers Chapter 6 - Pointers Outline 1 Introduction 2 Pointer Variable Declarations and Initialization 3 Pointer Operators 4 Calling Functions by Reference 5 Using the const Qualifier with Pointers 6 Bubble Sort

More information

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed? Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,

More information

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type- Lecture 3 Input and Output Review from last week Variable - place to store data in memory identified by a name should be meaningful Has a type- int double char bool Has a value may be garbage change value

More information

CMPS 221 Sample Final

CMPS 221 Sample Final Name: 1 CMPS 221 Sample Final 1. What is the purpose of having the parameter const int a[] as opposed to int a[] in a function declaration and definition? 2. What is the difference between cin.getline(str,

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays What we will learn about this week: Declaring and referencing arrays Arrays in memory Initializing arrays indexed variables arrays as function arguments Arrays a way of expressing many of the same variable

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Calling Functions by Reference 5.5 Using const with Pointers 5.6 Bubble

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2 Review Fall 2013 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2013 CISC2200 Yanjun Li 2 1 Array Arrays are data structures containing related data items of same type. An

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 2 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5. Calling Functions by Reference 5.5 Using const with

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Howaida Ismail Final Exam Spring 2013 Last Name :... ID:... First Name:...

More information

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1 300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard

More information

do { statements } while (condition);

do { statements } while (condition); Topic 4 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

PIC 10A. Final Review

PIC 10A. Final Review PIC 10A Final Review Final exam Thursday, December 18, 2014 8:00 AM - 11:00 AM MS 5200. In our usual class room. (Verify on my.ucla.edu!!) The final exam is worth 30% of your grade, same weight as 2 midterms.

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Khalil Final Exam Fall 2013 Last Name :... ID:... First Name:... Form

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

PIC 10A. Final Review: Part I

PIC 10A. Final Review: Part I PIC 10A Final Review: Part I Final exam The final exam is worth 30% of your grade, same weight as 2 midterms. Could be 50% if grading option 2 turns out better for you. Length is also roughly 2 midterms

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. CMPSC11 Final (Study Guide) Fall 11 Prof Hartman Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) This is a collection of statements that performs

More information