In: Computer Science
Suppose the interface and the class of stack already implemented, Write application program to ( java)
1- insert 100 numbers to the stack
2- Print the even numbers
3- Print the summation of the odd numbers
import java.util.Collections;
import java.util.Stack;
public class Main
{
//method to print even numbers of the stack
public static void printEven(Stack<Integer> s1){
//initialize ans array
int[] ans = new int[50];
int i = 0;
//loop runs untill all ements of the stack are popped out
while(s1.size() > 0){
int n = s1.pop();
//check is popped element is even or odd
//modulo operator returns the remainder of integer division
//if number is even then it is divisible by 2 so remainder is 0
if( n % 2 == 0)
{
//add number to the stack
ans[i] = n;
i++;
}
}
//prints all the even numbers
System.out.print("Even numbers: ");
for(int j = 0 ; j < i ; j++){
System.out.print(ans[j] + " ");
}
}
//method to print the sum of odd numbers of the stack
public static void printOddSum(Stack<Integer> s2){
int sum = 0;
while(s2.size() > 0){
int n = s2.pop();
//if number is even then add then prints the sum of all odd numbers
if( n % 2 != 0)
{
sum = sum + n;
}
}
//now the sum of all even numbers are stored in sum
System.out.println("Sum of Odd numbers: " + sum);
}
public static void main(String[] args) {
//initialize Stack s1 and s2
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
//push 100 elements in stack s1 and s2
for(int i = 0 ; i< 100 ; i++){
s1.push(i);
s2.push(i);
}
//prints the stack content
System.out.println("Stack" + s1);
//call printOddSum
printOddSum(s1);
// call printEven method
printEven(s2);
}
}
OUTPUT: