Showing posts with label Fibonacci. Show all posts
Showing posts with label Fibonacci. Show all posts

Java Swing Example - Fibonacci Generation - JList - JOptionPane - NetBeans - Internet & Web Programming Lab

Java Swing Example 
Fibonacci Generation 
JList - JOptionPane 
NetBeans - Internet & Web Programming Lab

Source code:
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/*
 * Fib2.java
 *
 * Created on Jan 21, 2012, 11:00:27 AM
 */
/**
 *
 * @author nn
 */
public class Fib2 extends javax.swing.JFrame {
    
    DefaultListModel dl;
    /** Creates new form Fib2 */
    public Fib2() {
        super("Fibonacci Series Generation");
        initComponents();
        dl = new DefaultListModel();
        jList1.setModel(dl);
       
    }

    /** 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() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        jLabel1.setText("Number of Terms");

        jLabel2.setText("Fibonacci Numbers");

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        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(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))))
                .addGap(92, 92, 92)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(45, 45, 45))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(16, 16, 16)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                        .addGap(27, 27, 27))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(3, 3, 3)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(69, 69, 69))))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        
        if(jTextField1.getText()!= null)
        {       
            dl.removeAllElements();
            int n=Integer.parseInt(jTextField1.getText());
            int ch = JOptionPane.showConfirmDialog(rootPane, "Generate "+n+ " fibonacci numbers ?");
            //System.out.print(ch);
        //String n1 = JOptionPane.showInputDialog("Enter n:");
            if(ch==0)
                 genfib(n);
        }
    }
void genfib(int n)
{
    int t1=0,t2=1,t3;
    if(n>=1)
    {
        dl.addElement(t1);
        
    }
    if(n>=2)
    {
        dl.addElement(t2);
        
    }   
     if(n>2)
    {
        for(int i=2;i<n;i++)
        {
            t3=t1+t2;
            dl.addElement(t3);
            t1=t2;
            t2=t3;
            //System.out.print(t3);
        }
    }
        
}
    /**
     * @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(Fib2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Fib2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Fib2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Fib2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Fib2 f1 = new Fib2();
                f1.setVisible(true);
                f1.setSize(600,500);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}


Output:



Inter Process Communication using Pipe- Fibonacci - Systems Lab - C

Program:
#include<stdio.h>
main()
{
    int pid;
    int p1[2],p2[2];
    pipe(p1);
    pipe(p2);
    int b,n,i,f1,f2;int ar[30],br[30];
    pid=fork();
    if(pid==0)
    {
        printf("enter count:");
        fflush(stdin);
        scanf("%d",&n);
        close(p1[0]);
        write(p1[1],&n,4);
       
        close(p2[1]);
        read(p2[0],br,30*sizeof(int));
        printf("\nFibonacci:\n");
        for(i=0;i<n;i++)
            printf("%d\n",br[i]);
           
    }
    else if(pid>0)
    {
    close(p1[1]);
    read(p1[0],&b,4);
    //printf("count is:%d",b);
   
    f1=0,f2=1;
    ar[0]=0;
    ar[1]=1;
    int i;
    for(i=2;i<b;i++)
    {
        int f3=f1+f2;
        f1=f2;
        f2=f3;
        ar[i]=f3;
    }
    close(p2[0]);
    write(p2[1],ar,30*sizeof(int));
    }
}


Output:
nn@ubuntu:~$ gcc pp.c
nn@ubuntu:~$ ./a.out
enter count:5
nn@ubuntu:~$
Fibonacci:
0
1
1
2
3

Generation of Fibonacci Series - Recursion & Iteration -LISP

Program:
;;FIBONACCI SERIES
(defun fib(n)
    (setf a 0 b 1)
    (format t "~&<<<Generation of Fibonacci series with ~D terms>>>~&1.Iterative method~&2.Recursive method~&Enter your choice:" n)
    (setf x (read))
    (cond
        ((= n 1) (print a))
        ((= n 2) (print a)(print b))
        ((> n 2) (if (= x 1)
                (fib1 n))
        (if (= x 2)
             (do ((i 0 (+ i 1))) ((= i n))
                (print (fib2 i)))))
    )
)
(defun fib1(n)
                ;Iterative method
    (print a)(print b)
    (do((i 2 (+ i 1))) ((= i n))
        (setf c (+ a b))
        (print c)
        (setf a b b c))
)
(defun fib2(n)
    (cond
        ((= n 0) 0)
        ((= n 1) 1)
        ((> n 1)(+ (fib2 (- n 1)) (fib2 (- n 2))))
                ;Recursive method
    )
)

Output:
Break 2 [3]> (load 'f.lsp)
;;  Loading file f.lsp ...
;;  Loaded file f.lsp
T
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:1

0
1
1
2
3
NIL
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:2

0
1
1
2
3
NIL
Break 2 [3]>

Generation of Fibonacci Series -Assembly Language - MASM

Program:
.model small
.stack 300H
.data
 msg1 DB 10,13,'Entre the count: $'
 msg2 DB 10,13,'FIBANACCI SERIES:  $'
 newline DB 10,13,'$'
 comma   DB ',$'
 prev1 DW 1
 prev2 DW 0
.code
   print MACRO msg                    ;macro definition
        PUSH AX
        PUSH DX
        MOV AH,09H
        MOV DX,offset msg
        INT 21H
        POP DX
        POP AX
        ENDM
.startup
       print msg1
       call readnumtoAX
       mov cx,ax                    ;program body
       mov ax,0                   
       print newline
       print msg2
       call displayAX
       print comma
       dec cx
       jz done
       mov ax,1
       call displayAX
       print comma
       dec cx
       jz done
repeat1:
       mov ax,prev1
       add ax,prev2
       call displayAX
       print comma
       mov bx,prev1
       mov prev2,bx
       mov prev1,ax
       loop repeat1
 done:
.exit
 readnumtoAX PROC NEAR ;STORE NUM. TO AX PROCEDURE DEF.
PUSH BX
      PUSH CX
      MOV CX,10
      MOV BX,00
 back:  MOV AH,01H
        INT 21H
        CMP AL,'0'
        JB skip
        CMP AL,'9'
        JA skip
        SUB AL,'0'
        PUSH AX
        MOV AX,BX
        MUL CX
        MOV BX,AX
        POP AX
        MOV AH,00
        ADD BX,AX
        JMP back
skip:
         MOV AX,BX
         POP CX
         POP BX
         RET
      readnumtoAX ENDP
displayAX PROC NEAR                       ;DISPLAY PROCEDURE CONTENTS OF AX
     PUSH DX
     PUSH CX
     PUSH BX
     PUSH AX
     MOV CX,0
     MOV BX,10
back1:  MOV DX,0
        DIV BX
        PUSH DX
        INC CX
        OR AX,AX
        JNZ back1
back2:  POP DX
        ADD DL,30H
        MOV AH,02H
        INT 21H
        LOOP back2
        POP AX
        POP BX
        POP CX
        POP DX
        RET
displayAX ENDP
END

Output:

F:\hwlab>edit fibonacci.asm
F:\hwlab>masm fibonacci.asm
F:\hwlab>link fibonacci.obj
F:\hwlab> fibonacci
Enter the count: 5
FIBONACCI SERIES: 0,1,1,2,3,
F:\hwlab> fibonacci
Enter the count:10
FIBONACCI SERIES: 0,1,1,2,3,5,8,13,21,34,

Generation of Fibonacci Series -C Program

Program:
#include<stdio.h>
//#include<conio.h>
void main()
{
    int a[200];int i,n,t1=1,t2=1,t3,x,y;//clrscr();
    a[1]=1;a[2]=1;
    printf("Enter the no of terms:");
    scanf("%d",&n);
    if(n<=0)
        printf("Error..!");
    else if(n==1)
        printf("The fibonacci series:\n1");
    else if(n==2)
        printf("The fibonacci series:\n1,1");
    else
        printf("The fibonacci series:\n1,1");
        for(i=3;i<=n;i++)
            {
                t3=t1+t2;
                t1=t2;
                t2=t3;
                printf(",%d",t2);
                a[i]=t3;
            }
    printf(",...\n");
    //getch();
}

Output:
nn@linuxmint ~ $ gcc c4.c
nn@linuxmint ~ $ ./a.out
Enter the no of terms:5
The fibonacci series:
1,1,2,3,5,...
nn@linuxmint ~ $
Related Posts Plugin for WordPress, Blogger...