What's new

.NET C# - The Benefits of the Stack Data Structure

Chris7S

Chris7S

Nerd by definition, programmer by trade
Grammar Nazi Chatty Kathy Seasoned Veteran
Messages
1,506
Reaction score
490
Points
515
Sin$
7
As most of the other developers here know that the Stack data structure is a LIFO(Last in, First out) structure. I have come across a few good uses for this but the simplest one that I could think of to talk about is a decimal to binary converter. The reason this structure is perfect for this operation is that after performing the calculations, you must invert the remainder results to reach the binary value of the given decimal. To teach some of the other users that do not know about this data structure I am going to share with you a snippet of code so you can see how it works! I hope someone learns from this and any comments on the code or concept please feel free to drop a comment! Also, I wrote this in about ten minutes so none of the code is documented. If you have any questions about what the code is doing comment below as well!

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DecimalToBinary
{
    class Program
    {
        static void Main(string[] args)
        {
            int Decimal = 0;

            Console.WriteLine("Enter a decimal to convert to binary:");
            Decimal = Int32.Parse(Console.ReadLine());

            Console.WriteLine("\nThe binary value of {0} is {1}\n\nPress any key to exit", Decimal, ToBinary(Decimal));

            Console.ReadKey();
        }

        public static string ToBinary(int Decimal)
        {
            Stack<int> stack = new Stack<int>();
            string result = "";
            int myDecimal = Decimal;
            int quotient, remainder, StackSize;
          
            while(myDecimal > 0)
            {
                quotient = (myDecimal / 2);
                remainder = (myDecimal % 2);
                myDecimal = quotient;
                stack.Push(remainder);
            }

            StackSize = stack.Count;

            for (int i = 0; i < StackSize; i++ )
            {
                result += stack.Pop();
            }

            return result;
        }
    }
}

I also wrote this in Java using stack as well. I created a JFrame project so there is a lot of skeleton code but the code driving the application is in the Convert() method (line 85-120).

Java:
import java.util.Stack;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Chris
 */
public class BinaryConverterUI extends javax.swing.JFrame {
   
    String result = "";
   
    /**
     * Creates new form BinaryConverterUI
     */
    public BinaryConverterUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Binary Converter");

        jLabel1.setText("Decimal");

        jButton1.setText("Convert");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        Convert();
    }                                        

    public void Convert()
    {
        result = "";
       
        try
        {
            Stack myStack = new Stack();
            int decimal = Integer.parseInt(jTextField1.getText());
            int quotient, remainder;

            while(decimal > 0)
            {
                quotient = (decimal / 2);
                remainder = (decimal % 2);
                decimal = quotient;
                myStack.push(remainder);
            }

            int StackSize = myStack.size();

            for (int i = 0; i < StackSize; i++)
            {
                result += myStack.pop().toString();
            }
           
            jLabel2.setText("The binary value of " + jTextField1.getText() + " is " +  result);
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
        }    
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BinaryConverterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BinaryConverterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BinaryConverterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BinaryConverterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BinaryConverterUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                  
}
 
Last edited:
Y

YYes

Enthusiast
Messages
177
Reaction score
52
Points
85
Sin$
7
Pretty cool. A project in a lot of CS classes is to write your own heap and stack and swap, etc., etc. Here are some examples of binary to decimal converters that build a stack with the system stack pointer and recursion, rather than a stack on the stack (stackception).

Code:
module Main where

main :: IO ()
main = do
  putStrLn "Enter a decimal to convert to binary:"
  numStr <- getLine
  putStrLn $ "The binary value of " ++ numStr ++ " is " ++ toBinary (read numStr :: Int)
  putStrLn "\nPress any key to exit"
  getLine
  return ()

toBinary n
  | n > 0 = toBinary (n `div` 2) ++ show (n `mod` 2)
toBinary _ = []

C#:
using System;

namespace DecimalToBinary
{
    class Program
    {
      static void Main(string[] args)
      {
           Console.WriteLine("Enter a decimal to convert to binary:");
           string numStr = Console.ReadLine();
           Console.WriteLine("The binary value of " + numStr + " is " + toBinary(int.Parse(numStr)));
           Console.WriteLine("\nPress any key to exit");
           Console.ReadLine();
           return;
       }

       private static string toBinary(int n)
       {
            if (n > 0)
                return toBinary(n / 2) + (n % 2).ToString();
            return "";
        }
    }
}
 
Chris7S

Chris7S

Nerd by definition, programmer by trade
Grammar Nazi Chatty Kathy Seasoned Veteran
Messages
1,506
Reaction score
490
Points
515
Sin$
7
Pretty cool. A project in a lot of CS classes is to write your own heap and stack and swap, etc., etc. Here are some examples of binary to decimal converters that build a stack with the system stack pointer and recursion, rather than a stack on the stack (stackception).

Code:
module Main where

main :: IO ()
main = do
  putStrLn "Enter a decimal to convert to binary:"
  numStr <- getLine
  putStrLn $ "The binary value of " ++ numStr ++ " is " ++ toBinary (read numStr :: Int)
  putStrLn "\nPress any key to exit"
  getLine
  return ()

toBinary n
  | n > 0 = toBinary (n `div` 2) ++ show (n `mod` 2)
toBinary _ = []

C#:
using System;

namespace DecimalToBinary
{
    class Program
    {
      static void Main(string[] args)
      {
           Console.WriteLine("Enter a decimal to convert to binary:");
           string numStr = Console.ReadLine();
           Console.WriteLine("The binary value of " + numStr + " is " + toBinary(int.Parse(numStr)));
           Console.WriteLine("\nPress any key to exit");
           Console.ReadLine();
           return;
       }

       private static string toBinary(int n)
       {
            if (n > 0)
                return toBinary(n / 2) + (n % 2).ToString();
            return "";
        }
    }
}
Nice man! I didn't even think about this as I was just showing how the Stack data structure could be used.
 
Top Bottom
Login
Register