CSCE - 1001 - RevisionSheet (2) 2
CSCE - 1001 - RevisionSheet (2) 2
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.
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
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
Sample Output:
0
1
1
0
B. If else / Switch
(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.
Continue? y
#include <iostream>
using namespace std;
int main ()
{
int n=1 , j=1;
#include <iostream>
using namespace std;
int main()
{
int array1[] = {1, 5, 7, 5, 8, 9, 11, 12};
int s1 =8;
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:
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.
#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;
}
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.
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:
test[0][0]=2
test[0][1] = -5
test[1][0]=4
tesst[1][1] = 0
test[2][0]=9
test[2][1]=1
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
Define a recursive function factorial that takes a positive integer number n and returns its factorial.
Test your function factorial for n = 5.
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().
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
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.
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
// 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();
};
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:
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);
}
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;
}
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”.
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