0% found this document useful (0 votes)
23 views21 pages

Revision Problems

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views21 pages

Revision Problems

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

CSCE 1001 Revision Problems

I – Introduction and Number Systems


Tick only one possible answer for each of the following:
1) The Central Processing Unit (CPU) is composed of:
a. RAM & ROM [ ]
b. Control Unit & Arithematic/Logic Unit [ ]
c. Main Memory & Registers [ ]
d. none of the above [ ]
2) In binary: 1111 + 1111 = ?
a. 11010 [ ]
b. 11110 [ ]
c. 11111 [ ]
d. none of the above [ ]
3) The software that controls and manages the computer resources is:
a. Linker [ ]
b. Loader [ ]
c. Web browser [ ]
d. Operating system [ ]
4) (47)10 is equivalent to:
a. (110000)2 [ ]
b. (110001)2 [ ]
c. (101111)2 [ ]
d. None of the above [ ]
5) (CA)16 is equivalent to:
a. (1010101)2 [ ]
b. (10101100)2 [ ]
c. (11001010)2 [ ]
d. None of the above [ ]
6) The binary: 100001100 is equivalent to:
a. (406)10 [ ]
b. (10F)16 [ ]
c. (10C)16 [ ]
d. none of the above [ ]
7) The ALU is the unit of computer responsible of:
a. Storing programs and data permanently [ ]
b. Performing arithmetic and logical operations [ ]
c. Performing Input/Output operations [ ]
d. None of the above [ ]
8) The part of the computer that temporary stores programs and data to be processed is:
a. The CPU [ ]
b. ROM [ ]
c. RAM [ ]
d. ALU [ ]
9) The Compiler is a software that:
a. translates a high-level language program into machine language [ ]
b. translates an assembly language program into machine language [ ]
c. lets users display and view a web document [ ]
d. None of the above [ ]
10) (111110)2 is equivalent to:
a. (63)10 [ ]
b. (62)10 [ ]
c. (F5)16 [ ]
d. None of the above [ ]

II – C++ Basics and Control Flow


1. An AUC staff recently signed a 3-year contract that included a salary increment of 7, 6, and 5%,
respectively, for the next 3 years. Write a C++ program that allows a user to enter the current salary
and then prints the compounded salary (rounded to the nearest hundredth) for each of the next 3 years.
2. The arithmetic mean of two numbers is the result of dividing their sum by 2. The geometric mean of
two numbers is the square root of their product. The harmonic mean of two numbers is the arithmetic
mean of their reciprocals. Write a C++ program that takes two real numbers as inputs and displays these
three means.

3. Write a C++ program that takes the radius of base and height of a cylinder to compute and display area
of base and volume of the cylinder rounded to the nearest hundredth according to the following
formulas:
Area of base = π x Radius2
Volume of cylindar = π x Radius2 x Height

4. In a laboratory, the time of an experiment is measured in seconds. Write a C++ program to enter the
time as an integer number of seconds, convert and print out it as a complete integer number of hours,
complete integer number of minutes and remaining seconds (if any).

5. The Pythagorean Theorem states that the sum of the squares of the sides of a right triangle is equal to
the square of the hypotenuse. For example, if two sides of a right triangle have lengths 3 and 4, then
the hypotenuse must have a length of 5. The integers 3, 4, and 5 together form a Pythagorean triple.
There is an infinite number of such triples. Given two positive integers, m and n, where m > n, a
Pythagorean triple can be generated by the following formulas.

Side1 = m2- n2
Side2 = 2mn
Hypotenuse = √𝑺𝒊𝒅𝒆𝟏𝟐 + 𝑺𝒊𝒅𝒆𝟐𝟐

Write C++ program that reads in values for m and n and prints the values of the Pythagorean triple
generated by the formulas above.

6. Write the C++ statements for the following algebraic formulas:


Algebraic Formula C++ statements
𝟏
V = 𝟑 𝝅𝒓𝟐

7. Trace the following program segments:


double a = 1.5, b = 2.0, c = 2.5; const int n = 6;
int L[n] = {3, 5, 5, 4, 9, 9};
int x = 6, y = 4.5, s = 5.68; bool flag = true;
cout.precision(2); int k = 0;
while ( (k < n-1) && (flag) )
if ( y > 4 ) {
cout << “Error!!” << endl;
if (L[k] > L[k+1])
else
{ c = (x + y) / (x + 1) * (a + 1) + 3.789; { flag = false;
cout << setw(2) << k << setw(2) <<L[k] << endl;
a = x % y + 2 * b + 3.783; }
else
if (y % x == 0) k++;
s = y / x + 3.789; }
else if (flag)
s = y % x + 3.789; cout << “ The list is sorted” << endl;

cout << “Value of c = “ << c << endl;


cout << “Value of a = “ << a << endl;
cout << “Value of s = “ << s << endl;
}

for (int k = 1; k < 5; k++) int a = .., b = .., c = ..; // a, b, and c are assigned some values
{ for (int j = 1; j < 5; j++) if ((a == b) && (a != b ))
switch ( k % 3 ) cout << “It is the first case!!”<< endl;
{ case 0: else
cout << setw(2) << if ((c == b) || (c != b ))
‘@’; cout << “It is the second case!!”<< endl;
break; else
case 1: cout << “It is the third case!!”<< endl;
cout << setw(2) << j;
break;
default:
cout << setw(2) <<
‘#’;
}
cout << endl;
}
int num = 182348, s = 9, g = 0, d;
const int ten = 10;
do
{ d = num % ten;
if ( d < s )
s = d;

if ( d > g )
g = d;
num = num / ten;
} while ( num != 0 );
cout << “Value 1 = “ << s << endl;
cout << “Value 2 = “ << g << endl;
cout << “Value 3 = “ << num << endl;

8. Write a C++ main function that takes and validates a big integer number between 999 and 999999 to
compute and display the sum and count of its even digits and only the sum of its odd digits.

9. Write only the C++ loop to generate each of the following sequences:
5 7 10 14 15 20 21 25 28 30 35
2 1 1 2 0 2 0 1 1 0 2
10. Write a C++ program that takes and validates a positive integer number between 0 and 99999
(inclusive) to notify the user with the message "ONE SINGLE DIGIT" if the number has only one digit,
"TWO BIG DIGITS" if the number has two digits, "THREE BIG DIGITS", if the number has three
digits, or “MORE AND MORE DIGITS”, if the number has more than three digits.

11. There are 900 people in a town whose population increases by 10 percent each year. Write a C++
program that displays the annual population and determines how many years (countYears) it will take
for the population to pass 20,000.

12. Write C++ loops to reproduce each of the shown output:

1 1 0 0 0 1 2 3 4 1 2 4 8
## 0 0 5 6 7 8 16 32 64 128
123 0 1 0 0 0 0 9 10 11
#### 0 0 1 0 0 0 12
12345 0 0 0 1 0 0 13 14 15 16
###### 0 0 0 0
1234567 1 0
######## 0 0 0 0 0 1

III – Arrays
1. Write only the C++ code to create the following array and and fill it with the shown data. Also, the the
code to display the array content as a 2D array.

A X X X X
X A X X X
X X A X X
X X X A X
X X X X A

2. Write only the C++ code to create the following array and and fill it with the shown data. Also, the the
code to display the array content as a 2D array.

A X X X X
A A X X X
A A A X X
A A A A X
A A A A A
13. 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.
Your program should ask the user to input all the numbers in your 3x3 matrix, the output
whether the input matrix is a magic square or not.

IV – Functions & Recursion


3. Define a C++ function MAX that takes three numbers and returns the largest one.

4. Define a C++ function MaxMin that takes three numbers and returns the largest and smallest ones.

5. Define a C++ function SUM_DIGITS that takes a positive integer number and returns back the sum of
its digits.

6. Define a C++ function EXISTS that takes two integer numbers, the first is a big number and the second
is one single digit. The function returns true if the single digit does exist in the big number and false
otherwise.

Write a recursive version of the function Exists.

7. Write a C++ function Occ that takes two positive integer numbers, the first is a big positive integer number
(BIG) and the second is a single digit d. The function returns the occurrence of the single digit d in the big
number BIG.

8. Define a C++ function Validate_Binary that takes a binary number (composed of 1’s and 0’s) to check
such number. The function returns true if the number is composed only of 0’s and 1’s, and false,
otherwise.

9. Write a C++ function GRADE that inputs a student’s average and returns the letter grade ‘A’ if a student’s
average is 90-100, ‘B’ if the average is 80-89, ‘C’ if the average is 70-79, ‘D’ if the average is 60-69, and
‘F’ if the average is lower than 60. Define the function twice, once using nested-if and second using
switch statement.
10. Write a C++ function that finds and returns the second largest element in an array of doubles.

11. Define modular C++ program that performs the following:


a. Takes and stores names and GPAs of n students in an array. The number of students n is a user input
between 10 and 50. The input of names is done by a function Input.
b. Call a function Sort to reaarange the list in an ascending alphabetic order according to the name of the
student. Define the necessary sawpping functions to swap both the names and GPAs.

12. The ancient Greek Euclid developed a method for finding the Greatest Common Divisor (GCD) of two
integers A and B (A greater than B). His method is:
a. If the remainder (R) of A / B is 0, then B is the GCD.
b. If it is not 0, then assign B to A and the remainder (R) to B.
c. Return to step 1 and repeat the process.

Write a modular C++ program that takes two integer numbers N and M and prints out their GCD. The
program should be structured as three functions: the main, swap and GCD. The main function takes two
integer numbers N and M and if N < M it calls the function swap that will interchange the values of N and
M (N is assigned to M and M is assigned to N). Then, the function main calls the function GCD that
receives the values of N and M as A and B, performs Euclid’s process (defined above) and returns the
corresponding GCD value to the main function that prints it out.
Write a recursive version of the function GCD.

13. Consider the following array A[ ] of integers:

5 3 1 2 0 6 2 8

a. Write a C++ recursive function that prints the contents of the array A from location 0 through location
7. Show a sample call for such function
b. Write a C++ recursive function that returns the sum of the contents of the array from location 0
through location 7. Show a sample call for such function.
c. Write a C++ recursive function that returns the number of non-zero elements in the array from
location 0 through location 7. The Show a sample call for such function.
d. Write a C++ recursive function to perform a recursive linear search. It searches for an input number
x in the input array from location 0 through location 7. The function returns the location of x in the
array if found, or -1, otherwise.

14. Write a recursive function, findSum, that calculates the sum of successive integers starting at 1 and ending
at n (that is, findSum(n) = (1 + 2 + 3 + … + (n -1) + n).

Problems 3
15. In Mathematics, factorial of an integer number n is referred to as n! and is defined as follows:

n! = n x (n-1) x (n-2) x ……x 3 x 2 x1 for n > 1, and


0! = 1
Also, consider the following:
n! = n x !(n-1) and

n! = n x !(n-1) = n x (n-1) x !(n-2) = n x (n-1) x !(n-2) x ……x 0! Where 0! = 1

For example:

4! = 4 x !3 = 4 x 3 x !2 = 4 x 3 x 2 x 1! = 4 x 3 x 2 x 1 x 0! Where 0! = 1

Define a recursive function factorial that takes a positive integer number n and returns its
factorial. Test your function factorial for n = 5.

16. Define a recursive function power (Y, n) that computes Yn where Y and n are positive integer numbers.
Consider the following rule:

Yn = Y x Yn-1 = Y x Y x Yn-2) x … x Y1 x Y0 where Y0 = 1

Test the the power function for Y = 5 and n = 3.

17. Extend the recursive function power to accept the following:


The value of base Y can be integer zero or more, and
The value of power n can be positive, negative, or zero integer.

18. Define a recursive function sumOfArray that takes an array A of size n to compute and return back the
sum of its elements.
Consider the following rule:
Sum of array A of n elements = A[n-1] + sum of array A of (n – 1) elements

19. Show the output of each of the following program segments:


int B[10] = {1.5, 1}; k = 1; int FCT (int);
do void main()
{ { int A[10] = { 2.5, 0, 4, 6, 8 };
k++; for ( int c = 0; c < 3; c++ )
B[k] = B[k-1] + B[k-2]; cout << setw(3) << A[c] << setw(4) << FCT(A[c]) << endl;
} while ( B[k] < 13 );
} // end main function
for ( int c = 0; c < k; c++ )
cout << setw(3) << B[c]; int FCT ( int n )
cout << endll << “END!! << endl; { int f = 1;
for ( int c = 2; c <= n; c++)
f = f * c;
return f;
} // end FCT function
void swap(string& a, string& b) bool validateB (int);
void main() void main()
string A[10] = {“Hassan”, “Amr”, “Dina”, “Ahmed”}; { int num[10] = {1001, 120, 103, 101, 100};
int n = 4;
for ( int r = 1; r < n; r++ ) for ( int k = 0; k < 4; k++)
for ( int c = 0; c < n – r; c++ ) if( validateB(num[k]) )
if ( A[c+1] < A[c] ) cout << setw(3) << k << setw(6) << num[k] << endl;
swap ( A[c], A[c+1] ) } // end function main

for ( int k = 0; k < n; k++ ) bool validateB ( int n )


cout << A[k] << endl; {
system (“pause”); const int ten = 10;
} // end main function while ( n != 0 )
void swap( string& a, string& b ) if ( n % ten > 1)
{ return false;
string Temp = a; else
a = b; n = n / ten;
b = Temp;
} // end swap function return true;
} // end function validate

int A[10], n = 29, num, index = 0; int getM (int, int, int);
const int two = 2; void main ()
cout << “The “ << setw(6) << n << “ is { int A[9] = {2, 6, 15, 11, 12, 6, 8, 9, 9}, B[3];
now “; for (int k = 2; k < 9 ; k = k+3)
do B[k/3] = getM(A[k-2], A[k-1], A[k]);
{ A[index] = n % two;
n = n / two; cout << “Final Content: “ << endl;
index++;
for ( int c = 0; c < 3; c++ )
} while (n != 0);
cout << B[c] << endl;
for ( k = index-1; k >= 0; k--)
cout << A[k]; system ("pause");
cout << endl << “Done!!” << endl; }
int getM(int a, int b, int c)
{ int M;
if ( a > b )
M = a;
else
M = b;
if ( c > M )
M = c;
return M;
}
int getOCC (int, int); bool myfunc(int n);
void main () void main()
{ int res, BIG = 50003; {
for (int d = 0; d < 10 ; d++) int A[5] = {2, 6, 5, 11, 12};
{ res = getOCC( BIG, d); for (int k = 0; k < 3 ; k++)
If ( res > 0 ) If (myfunc(A[k]))
cout << setw(5) << d << setw(5) << res << endl; cout << setw(4) << A[k];
} cout << endl;
system ("pause"); system ("pause");
} }
bool myfunc(int n)
int getOCC( long M, int n) {
{ int c = 0; const int ten = 10; For ( int c = 2; c <= n / 2; c++ )
do { if (n % c == 0)
if ( M % ten == n ) return false;
c++;
M = M / ten; return true;
} while ( M != 0 ); }
return c;
}

char A[4][4]; int DoD (int, int);

for ( int R = 0; R < 4; R++ ) int main ()


for ( int C = 0; C < 4; C++ ) { int X = 25, = Y 35;
if ( R != C ) cout << “Result = “ << DoD(25, 35) << endl;
A[R][C] = ‘ ‘; // space character return 0;
else } // end main function
if ( R % 2 == 0 )
A[R][C] = ‘0’; int DoD ( int A, int B )
else {
A[R][C] = ‘1’; if ( A > B )
return DoD( A-B, B);
for ( int R = 0; R < 4; R++ ) else
{ if ( B > A )
for ( int C = 0; C < 4; C++ ) return DoD(A, B-A);
cout << setw(2) << A[R][C]; else
cout << endl; if ( A == B )
} return A;
} // end DoD function
void reverse(int); int fibonacci(int);
int main () int main()
{ {
int num = 6789; int m = 4;
reverse( num ); cout << "The Fibonacci " << m << "th term =
cout << endl; " << fibonacci(m) << endl;
system ("pause"); system ("pause");
return 0; return 0;
} }
void reverse( int n ) int fibonacci (int n)
{ {
if (n != 0) if (n <= 2)
{ return 1;
cout << n % 10; else
reverse (n / 10); return fibonacci(n - 2) + fibonacci(n - 1);
} }
}

int Sum(int[], int); int strange(int);


int main() int main()
{ {
const int size = 5; int num = 5;
int x[size]; // array of 5 elements
cout << "The output = " << strange(num) << endl;
for (int i = 0; i < size; i++) system ("pause");
x[i] = i + 1; return 0;
cout << "sum = " << Sum(x, size); << endl; }
system ("pause"); int strange( int n )
return 0; {
} if (n == 1)
int Sum(int x[], int n) return 0; // stopping case
{ else
if (n == 1) return 1 + strange ( n / 2 );
return x[0]; // stopping case }
else
return x[n-1] + Sum(x, n-1);
}
V – File I/O Streams
1. 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;
}

1. An Instructor has recorded the grades of sn exam of his CSCE 1001 section (25 students) in a file
(“score.dat”) of two columns, the first contains the first name of the student (recorded without any
spaces) and the second contains his/her score (integer value ) as follows:

Karim 70
Ahmed 90
Zayed 75
Dina 80
Khaled 95
………. ….
………. ….

Youssef 66

Write a modular C++ program to perform the following:


a. Call a function “input” to read student’s data from the input file “score.dat” to be stored in two arrays
“name” and “score”.
b. Call a function “sort” that takes the two arrays “name” and “”score” to rearrange them in descending
order according to the value of score. Define necessary swap functions.
c. Call a function “output” that writes the content of the two sorted arrays “name” and “score” to an
output file “sortedScore.dat” using the same format of the input file “score.dat”.
d. Call a function “display” that displays on the screen the content of the file “sortedScore.dat”.
e. Redo the same problem using dynamic arrays.

VI – Pointers & Dynamic Arrays


1. Draw a diagram representing the execution of the following statements and give the output, if any.
Diagram Output

int *p, *q;

p = new int;

*p = 15.88;

q = new int;

*q = 23.8;

cout << *p << ” “ << *q << endl;

*p = *q;

cout << *p << ” “ << *q << endl;

p = q;

cout << *p << *q << endl;


2. Show the output of the following code with a user input 4 for the variable n.
typedef int* intPtr; intPtr A; int n;
cin >> n; // enter value for the variable n
A = new int[n];
for ( int c = 0; c < n; c++ )
{ A[c] = c;
cout << A[c] << endl;
}
Delete [] A;

3. Write a C++ program that find the common elements between two dynamic 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
4 7 11 3 9

8 1 4 12 10 7 2
Output:
4
7

VII – Classes and Structures

1. Assume that a new type has been defined as:


struct student
{
string name;
int totalPoints;
char letterGrade;
};
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.

3. 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;
}

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

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

6. 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 these 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 characteristics, 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.

VIII – Stacks & 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 queue


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.

______________________________________________________________________________
________________________________________________________________________

You might also like