0% found this document useful (0 votes)
2 views

Unit (13.1) Sorting[1]Hw4

Uploaded by

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

Unit (13.1) Sorting[1]Hw4

Uploaded by

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

‫جامعة تبوك‬

‫عمادة التعلم اإللكتروني والتعليم‬


‫عن بعد‬
(Practical)

Problem Solving in Computing

(Stack &&Que)

1. Assume that we want to find the sum of all elements in a stack of length 10.
Write and algorithm to find that sum?
1. Initialize sum to 0.
2. Repeat until the stack is empty:
o Pop the top element from the stack.
o Add the popped element to sum.
3. Return sum.

2. Assume that we have a stack of length 10. The stack contains integer numbers.
Write an algorithm to count the frequency of the value 3 in this stack.:
1. Initialize count to 0.
2. Repeat until the stack is empty:
o Pop the top element from the stack.
o If the popped element equals 3, increment count.
3. Return count.

4. Covert algorithm in question 2 into a program using C++ or Java?


C++ Program to count the frequency of the value 3 in a stack:

#include <iostream>
#include <stack>
using namespace std;

int countFrequency(stack<int> s, int value) {


int count = 0;
while (!s.empty()) {
if (s.top() == value) {
count++;
}
s.pop();
}
return count;
}
‫جامعة تبوك‬

‫عمادة التعلم اإللكتروني والتعليم‬


‫عن بعد‬
int main() {
stack<int> s;
// stack of length 10
int elements[10] = {3, 5, 3, 7, 3, 1, 2, 3, 8, 3};
for (int i = 0; i < 10; i++) {
s.push(elements[i]);
}

int targetValue = 3;
cout << "Frequency of " << targetValue << " in the
stack: " << countFrequency(s, targetValue) << endl;

return 0;
}

4. A queue of length 20 contains 20 even and odd numbers. Write an algorithm to


find the sum of those even numbers in that queue?
1. Initialize sum to 0.
2. For each element in the queue:
o Dequeue an element.
o If the element is even, add it to sum.
o Enqueue the element back to the queue.
3. Return sum.

You might also like