# Programming Revision Sheet

```The American University in Cairo
Department of Computer Science & Engineering
CSCE 1001
Fall 2018/2019
Final Exam Programming Revision Sheet
Basics, Control Flow, and Functions:
1. Show the output of the following
void test ( int, int&, int&);
int main( )
{
int d = 5, e = 6, f = 7, a = 8, b = 9;
test (d, e, f);
cout<<“In the main program after the 1st. call”<<endl;
cout<< “the variables are: “ <<setw(3) << e <<setw(3)
<< d <<setw(4) << f <<endl;
cout<< “----------------------------------------------“ <<endl;
test (a, b, f);
cout<<“In the main program after the 2nd. call”<<endl;
cout<< “the variables are: “ <<setw(3) << a <<setw(3)
<<b<<setw(4) << f <<endl;
return 0;
}
void test(int t, int& s, int& x)
{
s = 10;
s = s +20;
x = x + s + t;
t =3 * s;
cout<< “Function test Output: “ <<setw(3) << s
<<setw(3) << t <<setw(3) << x <<endl;
}
2. Trace the following and show the output:
int x=2, y=2;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;
x=1; y=1;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;
x=1; y=2;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;
x=2; y=2;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;
x=1; y=1;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;
x=1; y=2;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;
3. Write C++ program/ programs to reproduce each of the shown output:
1
\$\$
123
\$\$\$\$
12345
\$\$\$\$\$\$
1
0
0
0
0
0
0 0
1 0
0 1
0 0
0 0
0 0
0
0
0
1
0
0
0
0
0
0
1
0 1
0
0
0
0
0
1
2
5
6
9 10
13 14
3
7
11
15 16
4
8
12
1
16
2
32
===============================================================
4 8
64 128
4. Show the output of each of the following program segments:
a#include <iostream.h>
int main ()
{
int n=0;
for (int i=0; i<7; i++)
{
for (int j=0; j<=n; j++)
{
cout<<j;
}
n++;
cout<< endl
}
=============================================================
b#include <iostream.h>
int main ()
{
int n=1 , j=1;
for (int i=0; i<4; i++)
{
for (int k=j; k<=n*4; k++)
{
cout<<k;
}
n++;
j=j+4;
cout<< endl
}
}
c#include <iostream.h>
int main ()
{
int i=1;
while(i <= 128)
{
for (int k=0; k<4; k++)
{
cout<<i;
i=i*2;
}
cout<< endl
}
}
=============================================================
Arrays :
1. Write a C++ function that finds the second largest element in an array of doubles.
2. Write a C++ program that find the common elements between two arrays of variable
sizes. Your program should ask the user to input the sizes of the two arrays and the
elements in each of them. The program then should display the common elements
that
appear
in
both
arrays.
Sample Input:
Output:
4
7
4
7
11
3
9
8
1
4
12
10
7
2
3. Write a C++ program to check if a given 3x3 matrix comprises a magic square or not.
A magic square is a square where the sum of all the elements in each row, column
and diagonal is the same.
Example
2
7
6
3
4
8
9
5
1
5
7
1
4
3
8
9
2
6
Magic Square
Not Magic Square
The first square is a magic square as the sum of each row, column and diagonal is
equal (15), while the second is not a magic square as the sum of the first row (15) and
the sum of the second row (13) are not equal.
output whether the input matrix is a magic square or not.
4. Write a C++ function to transpose a matrix. Your function should accept two 2-D arrays
as parameters, one for the input and one for the output, verifies that the output array
dimensions match the expected ones for transposing the input array and populate it
with the matrix transpose by converting each row in the input matrix to a column in the
output matrix. The function should return either true or false based on whether the
transposition is possible for the passed input and output arrays or not.
Example
2
7
9
5
2
9
4
4
3
7
5
3
Input Matrix
Output Matrix
=============================================================
Recursion:
1) Write the recursive function int power(int num, int p) that calculates the value of
(nump). [Note: If p is 0, the function returns 1 and if p is 1 the function returns num].
2) Write a recursive function int handShake(int n) that calculates the number of
handshakes for n people in room, where n is a number greater than or equal to 2 and
every person handshakes with every other person in the room (the handshake between
persons a & b is counted as 1 handshake). Note that handShake(1) = 0 and
handShake(2) = 1.
3) Write 2 versions (recursive and non-recursive) of the function int sumDigits(int n)
that calculates the sum of the digits of the input parameter n.
4) Given the recursive function int factorial(num) below, trace the changing values of the
variables in the memory when the following function call is executed:
int x = factorial(5).
int factorial (int num) {
If (num == 0)
Return 1;
else
return (num*factorial(num-1));
}
=============================================================
Pointers and Dynamic Memory Allocation:
1. Write a C++ program that takes two integers from the user in variables num1 and
num2, then assigns pointer ptr1 to the address of num1 and ptr2 to address of num2.
Pass the two pointers to a function called ADD that adds the contents of the variables
pointed at by the two pointers then returns the sum to the main().
2. Write a C++ program that asks the user for the size of an array, then creates a dynamic
array of the input size using a pointer. The user then starts filling the array, then the
array is passed to a function that calculates the average of the numbers in the array
and returns the average value to the main. Delete the pointer when you are done.
3. What is the output of the following C++ code?
#include <iostream>
using namespace std;
int main() {
int a = 34, b = 62;
int *p1, *p2, *p3;
p1 = &a; p2 = &b;
p3 = p1;
p1 = p2;
p2 = p3;
cout << *p2;
return 0; }
a)
b)
c)
d)
62
34
4. What is the output of the following code?
int main() {
int *p1, v1 = 4, v2 = 9, *p2;
p1 = &v1;
p2 = &v2;
cout << v1 << “ “ << *p2 << endl;
cout << *p1 << “ “ << v2 << endl;
cout << (*p1 + v1 + *p2) << endl;
return 0;
}
=============================================================
Structures and Classes:
1.
Assume that a new type has been defined as:
struct student
{
string name;
int totalPoints;
};
Write a function that computes a student letter grade (A, B, C, D, or F) based on the cutoff
levels of 90%, 80%, 70%, 60%, and 50%. Show how this function can be used in a program
to set the appropriate member of a student structure.
2.
Assume that a new type has been defined as:
class counter
{
Public:
// Member functions
// Constructors
counter(); // default constructor, initializes member variable count to 0 and maxValue
to INT_MAX
counter(int); // constructor, initializes member variable count to 0 and maxValue to
argument value
void increment();
// Increment Counter
void decrement(); // Decrement Counter
void setCount(int); // Set Counter Value, not less than 0 and not greater than
maxValue
void setMaxValue(int);
// Set Maximum Counter Value, not less than 0 and not
greater than INT_MAX
int getCount();
// Return current counter value
int getMaxValue(); // Return maximum counter value
private:
int count;
// counter value
int maxValue; // maximum counter value
};
Write the complete definition of each member function.
Consider the counter class to add the following member functions:
a. Two type bool member functions called atMax and atMin that return a value of true
when the value of a counter object has reached its maximum value or its minimum
value (zero), respectively.
b. A type bool member function called lessThan that has a single int argument and
returns true if the counter object is less than the value of its argument.
c. The following member function lessThanC compares two counter objects and returns
true when the counter object it’s applied to has a smaller value than the counter
argument:
bool counter :: lessThanC( const counter& aCounter) const
{
if ( count < aCounter.count)
return true;
else
return false;
}
Extend the definition of the counter class by adding a member function
compareCounter that compares two counter objects and returns -1, 0, or 1 depending
on whether the count attribute of the counter object it’s applied to is less than (-1), or
equal to (0), or greater than (1), the count attribute of its counter argument.
3- Design and implement a Dice class . Each instance of this class should have as member
variables the die’s current side (number of dots) and the total number of times it has been
rolled. There should be an accessor member functions for of the two attributes. Two other
member functions roll and reset, are the modifier member functions. roll should use a random
number to determine the current side of a die. Develop the class for dice by writing formal
specifications including a default constructor and test it in a simple tester program.
4- In a graphics program, we need to represent simple graphical objects such as circles,
squares, rectangles, and triangles. We want to be able to position theses objects anywhere
on the screen and draw them in various sizes and colors. Besides drawing the objects
themselves, we want to display the object’s characterisitics, including the center coordinates,
area and perimeter.
a. Design a class that can be used to represent circle objects. The circle class should
have data members to represent the x- and y-coordinates of a circle object’s center as
well as the radius, area, and perimeter. Normally, a user of this class would set values
for all of a circle object’s member variables except the area and perimeter. These
attributes can be computed (using member functions) after the radius is set by the
class user.
b. Add a member function to the circle class to compute the distance between the center
of the circle object it’s applied to and the center of a circle argument.
c. Design a class that can be used to represent square objects. The square class should
have data members to represent the x- and y-coordinates of a square object’s center
as well as the side length, area, diagonal, and perimeter. Normally, a user of this class
would set values for all of a square object’s attributes except the area, diagonal and
perimeter. These attributes can be computed (using member functions) after the side
length is set by the class user.
=============================================================
Stacks and Queues:
1. Given the following basic stack implementation, answer the questions that show below:
/* C++ program to implement basic stack operations */
#include <iostream>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
int a[MAX]; //Maximum size of Stack
Stack();
bool push(int x);
int pop();
bool isEmpty();
};
Stack::Stack(){
top = -1;
}
bool Stack::push(int x)
{
if (top >= (MAX-1))
{
cout << "Stack Overflow";
return false;
}
else
{
a[++top] = x;
cout<<x <<" pushed into stack\n";
return true;
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
Stack s;
s.push(10); //Line 1
s.push(20); //Line 2
s.push(30); //Line 3
cout<<s.pop() << " Popped from stack\n";
//Line 4
return 0;
}
a. State three applications for the usage of stacks.
b. Show the content of the array called “a” implemented inside the stack after the
execution of lines 1, 2, 3, and 4 of the main function in the code above.
c. Add to the class above a function called void purge() that entirely eliminates the
contents of the stack.
d. Add to the class above a function called bool isFull() that returns true if the capacity of
the stack had reached its maximum capacity as indicated by MAX in the code above.
e. Add to the class above a function called void reverse() that reverses the content of the
stack in its entirety. So for example, if the stack contained from top to bottom 1, 5, 10,
19 now it will contain 19, 10, 5, 1 after a call to reverse().
2.The following is the code for a queue that is modelled using an array. The queue is
designed such that index 0 of the array is always the front of the queue. Back is a variable
that is used to designate where the end of the queue is. Answer the questions below:
/* C++ program to implement basic stack
operations */
#include <iostream>
using namespace std;
#define MAX 1000
class Queue
{
int back;
public:
int a[MAX]; //Maximum size of Stack
Queue();
bool enqueue(int x);
int dequeue();
bool isEmpty();
void print();
};
Queue::Queue(){
back = -1;
}
bool Queue::enqueue(int x)
{
if (back >= (MAX-1))
{
cout << "Queue Overflow";
return false;
}
else
{
a[++back] = x;
return true;
}
}
int Queue::dequeue()
{
if (back < 0)
{
cout << "Queue Underflow";
return 0;
}
else
{
int x = a[0];
for (int i=1; i<=back; i++){
a[i-1]=a[i];
}
back--;
return x;
}
}
bool Queue::isEmpty()
{
return (back < 0);
}
void Queue::print(){
cout << "Content of queue: ";
...
cout << endl;
}
// Driver program to test above functions
int main()
{
Queue q;
q.enqueue(10);
q.print();
q.enqueue(20);
q.print();
q.enqueue(30);
q.print();
q.dequeue();
q.print();
return 0;
}
a. This queue is designed such that the front of the queue is always at index 0 of the
array. While adding an element to the end of the queue is simple, understand the
code above to answer what the overhead is with removing an element from the
queue (dequeue)?
b. Add a function int peek() that simply gives you back the element at the beginning of
the queue without actually dequeueing it from the queue.
c. Add a function int size() that gives you back the number of elements inside the
queue (not the maximum possible size of the queue).
d. Complete the code for the print function above to print the content of the queue
without removing anything from the queue.
===========================================================
File I/O:
1. Write a modular C++ program that populates an array from an input file “infile.dat”, sorts
the array, writes down the sorted data in an output file “outfile.dat” and finally reads the
output file to be displayed on the screen. This program uses five functions: input, sort,
output, display and swap.
2.
What is the output of this code assuming that the three numbers in the “infile.dat” are
100, 200 and 300?
#include <fstream>
#include <iostream>
#include <cstdlib>
int main( )
{
using namespace std;
ifstream inStream;
ofstream outStream;
inStream.open("infile.dat");
if (inStream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
outStream.open("outfile.dat");
if (outStream.fail( ))
{
cout << "Output file opening failed.\n";
exit(1);
}
int first, second, third;
inStream >> first >> second >> third; outStream << "The average
of the first 3\n"
<< "numbers in infile.dat\n"
<< "is " << (first + second + third)/3
<< endl;
inStream.close( );
outStream.close( );
outStream.open("outfile.dat", ios::app);
outStream << "End of output file";
outStream.close( );
return 0;
}
cout << "*" << setw(5) << 123 << "*"
<< 123 << "*" << endl;
cout.setf(ios::showpos);
cout << "*" << setw(5) << 123 << "*"
<< 123 << "*" << endl;
cout.unsetf(ios::showpos);
cout.setf(ios::left);
cout << "*" << setw(5) << 123 << "*"
<< setw(5) << 123 << "*" << endl;
3. Write a modular C++ program that populates an array from an input file “infile.dat”, and
computes and display the sum of factorials of each of the numbers
included in the array in an output file “outfile.dat”. The function that
computes the sum of factorials should be a recursive function.
sum = 0! + 1! + 2! + 3! + ……… + n!
Where, the factorial is an integer function and factorial of m (m is a positive integer) is
referred to in mathematics as m! and defined as follows:
m! = m x (m-1) x (m-2) x ……x 3 x 2 x1 for m > 1, and
1! = 1 and 0! = 1
```
Arab people

15 Cards