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

CSCE - 1001 - RevisionSheet (2) 2

This document is a revision sheet for the CSCE 1001 examination, providing a variety of topics including basics of programming, control structures, loops, arrays, functions, and more. It includes sample questions and programming tasks to aid in preparation for the exam. The content is structured into sections that cover fundamental concepts and practical coding exercises.

Uploaded by

earthclubebis
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 views50 pages

CSCE - 1001 - RevisionSheet (2) 2

This document is a revision sheet for the CSCE 1001 examination, providing a variety of topics including basics of programming, control structures, loops, arrays, functions, and more. It includes sample questions and programming tasks to aid in preparation for the exam. The content is structured into sections that cover fundamental concepts and practical coding exercises.

Uploaded by

earthclubebis
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/ 50

CSCE 1001 Revision Sheet

Fall 2024

This is a revision sheet to help you prepare for the examination. The questions are
only a guide, and the actual questions showing up on the examination will vary in
type and complexity and may include different types of questions you have not seen
here. The exam may also include multiple choice questions that ask you what the
output of a given code is, what a code does, and what is wrong (logically) with a
given code that is supposed to achieve a certain purpose.

Thanks to all involved in preparing this sheet.

List of Contents:
A. Basics
B. If else / switch
C. Loops (all types of loops, patterns)
D. Arrays (static, dynamic, 1D, 2D)
E. Functions (Pass by value, Pass by reference, overloading)
F. Recursion
G. Pointers
H. Strings
I. Structs
J. Classes
K. Stacks
L. Queues
M. File I/O
A. Basics

1. Select the best answer:

1) The binary: 100001100 is equivalent to:


a. (406)10
b. (10F)16
c. (10C)16
d. none of the above

2) 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

3) The part of the computer that temporarily stores programs and data to be processed is:
a. The CPU
b. ROM
c. RAM
d. ALU

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

5) (111110)2 is equivalent to:


a. (63)10
b. (62)10
c. (F5)16
d. None of the above
2. Write a C++ program to check if two given non-negative integers have the same last digit.
Sample Input:
123, 456
12, 512
7, 87
12, 45

Sample Output:
0
1
1
0
B. If else / Switch

1. Write a program that determines a student’s grade.


The program will read three types of scores (quiz, mid-term, and final scores) and determine the
grade based on the following rules:

-if the average score = 90% => grade=A


-if the average score >= 70% and <90% => grade=B
-if the average score >= 50% and <70% => grade=C
-if the average score < 50% => grade=F

2. Trace the following code and show the output:

(a)
int x=2, y=2;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;

(b)
x=1; y=1;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;

(c)
x=1; y=2;
if(x == 1)
if(y==2)
cout<< "A" <<endl;
else cout<< "B" <<endl;
else cout<< "C" <<endl;
(d)
x=2; y=2;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;

(e)
x=1; y=1;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;

(f)
x=1; y=2;
if(x == 1)
{
if(y==2)
cout<< "A" <<endl;
}
else cout<< "B" <<endl;
cout<< "C" <<endl;
C. Loops

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

2. Write a C++ main function that inputs any number and validates that it is within [1,1000].
You are then to compute the average of the digits of that number. For example, if you input
978, the program will compute (9+7+8 / 3).

3. Write a program that will ask the user to input n positive numbers. The program will terminate
if one of those numbers is not positive.

4. Write a program that reads in ten whole numbers and that outputs the sum of all the numbers
greater than zero, the sum of all the numbers less than zero (which will be a negative or zero),
and the sum of all the numbers, whether positive, negative, or zero.

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

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

7. Using Switch Statement


Write a program that asks the user for an integer number in [1,10] and finds the sum of all integer
numbers up to that number starting from 1. For example, if you input 5, the program will
compute and output 1+2+3+4+5
8. Write a program that will prompt the user to choose the operation choice (from 1 to 5). Then
it asks the user to input two integer values for the calculation. The program also asks the user to
decide whether he/she wants to continue the operation. If he/she input ‘y’, the program will
prompt the user to choose the operation again. Otherwise, the program will terminate.

See the sample below:


MENU Add
Subtract
Multiply
Divide
Modulus
Enter your choice: 1
Enter your two numbers: 12 15
Result: 27

Continue? y

9. What is the output of the following program (without using a compiler):

#include <iostream>
using namespace std;
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;
}
}
10. Trace and show the output of the following code:

#include <iostream>
using namespace std;
int main()
{
int array1[] = {1, 5, 7, 5, 8, 9, 11, 12};
int s1 =8;

cout << "Original array: ";

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


cout << array1[i] <<" ";

int i, sum = 12, ctr = 0;

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


for (int j=i+1; j<s1; j++)
if (array1[i]+array1[j] == sum)
{
cout << "\n" << array1[i] << "," <<
array1[j]; ctr++;
}

cout << ctr;

return 0;
}
11. What is the output of each of the following code segments:

a.

b.

c.

d.
12. What is the output of each of the following C++ program segments:

a. for(int i = 1; i <= 9; i++)


{
for(int j = 1; j <= i; j++)
if(j < i)
cout << ' ';
else
cout << setw(2) <<'*';
cout << endl;
}

b. for(int i = 1; i <= 10; i++)


{
for(int j = 1; j <= 10-i+1; j++)
cout << setw(2) << '*';
cout << endl;
}

c. for(int i=1; i<=7; i++)


{
for(int j=1; j<=7-i; j++) //i = 1, j = 1 à 6
cout << ' ';
for(int j=1; j<i; j++) // i = 1, skip loop
{
cout<<'*';
}
cout<<'*'; // the middle star
for(int j=1; j<i; j++) // i = 1, skip loop
{
cout<<'*';
}
cout<<endl;
}

d. for(int i = 0; i <= 6; i++)


{
for(int j = 0; j <= i; j++)
cout << j;
cout << endl;
}
e. for(int i =1; i <= 6; i++)
{
for(int j =1; j <= i; j++)
if(i%2 ==0)
cout << "$";
else
cout << j;
cout << endl;
}

f. for(int i =1; i <= 5; i++)


{
for(int j =1; j <= 5; j++)
if(i!=j)
cout << setw(2) << '0';
else
cout << setw(2) << '1';
cout << endl;
}

g. int count = 1;
for(int i =1; i <= 4; i++)
{
for(int j =1; j <= 4; j++)
{
cout << setw(3) <<
count; count++;
}
cout << endl;
}

h. int count = 1;
for(int i =1; i <= 2; i++)
{
for(int j =1; j <= 4; j++)
{
cout << setw(4) << count;
count = count * 2;
}
cout << endl;
}
13. Write a program that produces the following patterns using for loops to standard output:

(a)
1
$$
123
$$$$
12345
$$$$$$

(b)
10000
01000
00100
00010
00001

(c)
01234
56789
98765
43210

14. Write a Complete program that uses nested loops to produce the following graphics.
Test That each of your programs actually produces the desired shape.

(a) (b) (c) (d)


1 1 1 2 4 8
1 $$ $$ 16 32 64 128
12 123 123
*** $$$$ $$$$
1234 12345 12345
12345 $$$$$$ $$$$$$
******
1234567
12345678
*********
15. Show the output of the following program segment for the following set of data:
6 3 9 0 0 19
16. What is the output of the following code:

#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print a mystery series:\n";
cout << " \n";
cout << " The series are: \n";
int nm1 = 1;
while (true)
{
++nm1;
if ((nm1 % 3) == 0)
continue;
if (nm1 == 50)
break;
if ((nm1 % 2) == 0)
{
nm1 += 3;
}
else
{
nm1 -= 3;
}
cout << nm1 << " ";
}
cout << endl;
return 0;
}
17. What is the output of the following programs (without using a compiler):

#include <iostream>
using namespace std;
int main ()
{
int n=0;

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


{
for (int j=0; j<=n; j++)
{
cout<<j;

}
n++;
cout<< endl;
}

}
D. Arrays

1. Write a C++ program that finds 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.

2. Write only the C++ code to create a 2D array with the dimensions below and fill the major
diagonal with the letter ‘A’. Also, display the array content as a 2D array on the screen.

3. Write only the C++ code to create the following 2D array and fill the part in blue with the letter
‘A’ and the part in white with the letter ‘X’.

4. Write a C++ program that finds 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:
4 7 11 3 9
8 1 4 12 10 7 2

Output:
47
5. Write a C++ program that will populate an array with the first n prime numbers. You are to
input n.

6. Write a C++ program to find the largest element of a given array of integers. (You can assume
any number you want)

7. Write a C++ program that accepts sales unit price and sales quantity of various items and
compute total sales amount and the average sales quantity. All input values must be greater than
or equal to 0 and less than or equal to 1,000, and the number of pairs of sales unit and sales
quantity does not exceed 100. If a fraction occurs in the average of the sales quantity, round the
first decimal place.

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

9. Let the array n be declared as follows:

What output is produced by the following:

adda
10. Write a C++ program to check a given array of integers of length 1 or more and return true
if the first element and the last element are equal in the given array.
Sample Input:
{10, 20, 40, 50}
{10, 20, 40, 10}
{12, 24, 35, 55}

Sample Output:
0
1
0

11. Write a C++ program to create a new array containing the middle elements from the two
given arrays of integers, each length 5.
Sample Input: int main() {
int arr1[5] = {0, 10, 20, 30, 40};
{0, 10, 20, 30, 40} int arr2[5] = {0, -10, -20, -30, -40};
{0, -10, -20, -30, -40}
// Middle is index 2 (because arrays start from 0)
Sample Output: int newArr[2];
newArr[0] = arr1[2];
New array: newArr[1] = arr2[2];
20 -20
cout << "New array: " << newArr[0] << " " << newArr[1] << endl;

12. Create a program segment that takes a 1-D array and reverses all its contents as shown
below. Example below:
13. Show the output of the following program segment:

14. Show the output of the following program segment:


15. Trace and show the output of the following program:

test[0][0]=2
test[0][1] = -5
test[1][0]=4
tesst[1][1] = 0
test[2][0]=9
test[2][1]=1

16. Trace and show the output of the following program:


17. After executing the below code, show the initial and final contents of each of
the elements of the array “A”:

int A[8] = {55,55,55,55,50,80,80,65} Initial Final


int T; bool cont = true;

int n= 8, j = 1; A A
while (j < 8 && cont) A[0]
{
If (A[j] > A[0]) A[1]
{ A[2]
T = A[0]; A[3]
A[0] = A[j]; A[4]
A[j] = T; A[5]
cont = false; A[6]
} A[7]
else
J++;
}
18. Show the content of the arrays A and B as a result of executing the following
program:
E. Functions

1. Trace the following programs, showing the change happening in each variable
in a tabular fashion over time, as well as any output to the screen.
2. Show the output of each of the following program segments:
3. Show the output of each of the following program:
4. Show the output of the following program segment:
5. Show the output of the following program segment:
6. Show the output of the following program segment:
7. Show the output of the following program:
8. Show the output of the following program:
9. Show the output of the following program segment:
10. Show the output of the following program segment:
11. Show the output of the following program segment:
12. 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 in C.1) and returns the corresponding GCD value to the main function that
prints it out. Write a recursive version of the function GCD.

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

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

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

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

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

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

19. Write a C++ function that finds and returns the second largest element in an array of doubles.

20. Write an “overloaded” function called absolute that converts a negative number of either int
or float to an absolute positive number.

21. Write a function that would change from Celsius degree to Fahrenheit according to the
following equation: F = C* 9/5 + 32
The function should be a void one and should have a call by reference. Also, please write the main
function to call it.
22. Write a function that would change from Celsius degree to Fahrenheit according to the
following equation: F = C* 9/5 + 32
The function should be a void one and should have a call by reference. Also, please write the main
function to call it.

23. Write two functions that would compute and return the perimeter and the area of the
rectangle. The area of the rectangle is area=width*height while perimeter is perimeter=
2(height+width).
Sample Input:
Input the width of the rectangle: 8.5
Input the height of the rectangle: 5.6
Sample Output:
The area of the rectangle is: 47.6
The perimeter of the rectangle is: 28.2

24. Write a C++ function to check two given integers and return true if one of them is 30 or if their
sum is 30.
Sample Input:
30, 0
25, 5
20, 30
20, 25
Sample Output:
1
1
1
0

25. Write a C++ program to check whether three given integer values are in the range 20..50
inclusive. Return true if 1 or more of them are in the said range otherwise false.
Sample Input:
11, 20, 12
30, 30, 17
25, 35, 50
15, 12, 8
Sample Output:
1
1
1
0
26. Write a function to check if three given numbers are in strict increasing order, such as 4 7 15,
or 45, 56, 67, but not 5 ,4, 8 or 6, 6, 8. However, if a fourth parameter is true, equality is allowed,
such as 6, 6, 8 or 7, 7, 7.

27. Create a function which validates a bridge is safe to walk on (i.e has no gaps in it to fall
through).
Examples: isSafeBridge(‘#’ ,’#’,’#’) is true
isSafeBridge(‘#’,’ ‘,’#’) is false

28. Write a C++ program (include a function in your answer) to add all the numbers from 1 to a
given number.
For example, if the number is 4, the functions adds the numbers from 1 to 4 (1+ 2+3 +4). Use the
function in the main program to Add 1 to 4 and Add 1 to 100.

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

30. Write a C++ function that takes a single dimensional array and finds the second largest
element in the array.

31. 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.
F. Recursion

1. Write a 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, 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).

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

4. 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. For example, if the input n=134, the
function should return 8 (1+3+4).

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

6. 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 power function for Y = 5 and n = 3.


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.
7. In Mathematics, factorial of an integer number n is referred to as n! and is defined as follows:

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

8. 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.
G. Pointers

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. What is the output of the following C++ code?

3. What is the output of the following C++ code?


H. Strings

1. Write a C++ program to input two strings. The program will then output the two strings
interleaved. For example, if you input “abc'' and “defghij”, the program will output adbecfghij.
If you input “defg”, and “abc”, the program will output “daebfcg”.

2. Write a C++ program that will input a string, and then output the corresponding string with each
letter as the one following it in the alphabet. For example, if you input abc, the program will output
bcd.

3. Write a C++ program that inputs a string and counts the number of words in that string and
prints it to the screen.

4. Write a C++ program that inserts a ‘-’ character between all words in the string. For example, if
you input “Good morning this is a lovely day”, the output on the screen will be:
“Good-morning-this-is-a-lovely-day”. Do not deal with punctuation marks.

5. Write a program that reads a string and eliminates all punctuation marks from the string and
outputs the result to the screen.
For example, if you input “Good morning, this is a great day!”, the output will be “Good morning
this is a great day”
I. Structs

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 manipulate
data stored in the appropriate member of a student structure.

2. Write a C++ program that performs the following:


a. Takes and stores names and GPAs of n students in an array of structs. The number of
students n is a user input between 10 and 50 inclusive. The input of names is done by a
function getNames.

b. Call a function Sort to rearrange the list in an ascending alphabetical order according
to the name of the student. Define the necessary swapping functions.
J. Classes

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


class counter
{
public:
//Data Members
// counter value
int count;
// maximum counter value
int maxValue;

// Constructors
// default constructor, initializes member variable count to 0 and maxValue to INT_MAX
counter();
// constructor, initializes member variable count to 0 and maxValue to argument value
counter(int);

// Member functions
// Increment Counter
void increment();
// Decrement Counter
void decrement();
// Set Counter Value, >=0, <maxValue
void setCount(int);
// Set Maximum Counter Value, >= 0 and <INT_MAX
void setMaxValue(int);
// Return current counter value
int getCount();
// Return maximum counter value private:
int getMaxValue();
};

a) Write the complete definition of each member function.


b) Add the following to the class:
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.
c) A member function lessThanC that compares two counter objects and returns true when the
counter object it’s applied to has a smaller value than the counter argument:
d) 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.
2. 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.

3. 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 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.
K. Stacks

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;
}
Undo/Redo in text editors (like Ctrl+Z and Ctrl+Y).

Backtracking in games or solving mazes.

Function call management in programs (when one function calls another).

a) State three applicationsvoid


for the() {usage of stacks.
purge
top = -1
}
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
void purge() {
top = -1;
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(). bool isFull ();

bool Stack::isFull(){
if (top> (MAX-1)) {
cout << “Stack reached maximum capacity” << endl;
return true;
}
else
return false;
L. Queues

1. 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:

#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;
}
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)?

a) Add a function int peek() that simply gives you back the element at the beginning of the
queue without actually dequeuing it from the queue.
b) Add a function int size() that gives you back the number of elements inside the queue (not
the maximum possible size of the queue).
c) Complete the code for the print function above to print the content of the queue without
removing anything from the queue.
a)
void Queue::print() {
int Queue::peek() {
b) int Queue::size() { cout << "Content of queue: ";
if (back < 0) {
return back + 1; for (int i = 0; i <= back; i++) {
cout << "Queue is empty";
} cout << a[i] << " ";
return 0;
}
} else {
cout << endl;
return a[0]; // first element in queue
}
}
M. Files I/O

1. Write a 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>
using namespace std;

int main( )
{
ifstream inStream; like declaring int x but variable intStream to read
ofstream outStream;
inStream.open("infile.dat"); ur telling the program to use inStream to open the file, just like you’d use a mouse to double-click and open a file on your computer.
if (inStream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
outStream.open("outfile.dat"); ur telling the program to use outStream to open the file, just like you’d use a mouse to double-click and open a file on your computer.
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;
}
3. Write a C++ program that populates an array from an input file “infile.dat” and computes and
displays the sum of factorials of each of the numbers included in the array in an output file
“outfile.dat”.

For example, infile.dat can have the following:


4
3
6
1
3

Then outfile.dat will have a single value for: 4! + 3! + 6! + 1! + 3!

4. An Instructor has recorded the grades of an 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”. Redo the same problem using dynamic arrays.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy