Source Code : Triangular numbers with stack replaces recursion
Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com.
Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com.
Click Here or search from google with Libraries Name you get jar file related it
Triangular numbers with stack replaces recursion

import java.io.IOException;
public class TriangleStack {
static int num;
static int ans;
static Stack theStack;
public static void main(String[] args) throws IOException {
num = 100;
stackTriangle();
System.out.println("Triangle=" + ans);
}
public static void stackTriangle() {
theStack = new Stack(10000); // make a stack
ans = 0; // initialize answer
while (num > 0) // until n is 1,
{
theStack.push(num); // push value
--num; // decrement value
}
while (!theStack.isEmpty()) // until stack empty,
{
int newN = theStack.pop(); // pop value,
ans += newN; // add to answer
}
}
}
class Stack {
private int maxSize; // size of stack array
private int[] data;
private int top; // top of stack
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}
public int pop() {
return data[top--];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
Thank with us