Friday, August 10, 2018

SIMPLE JAVA PROGRAMS PART 2 FOR BEGINNERS

PROGRAM TO PRINT GCF/HCF FOR THE GIVEN NUMBERS:

STATEMENT:

The program must accept two numbers X and Y and then print their HCF/GCD.

PROGRAM:


import java.util.*;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int X = sc.nextInt();

        int Y = sc.nextInt();

        while (X != Y) {

            if (X > Y) {

                X = X - Y;

            } else {

                Y = Y - X;

            }

        }

        System.out.print(X);
    }
}


Input:
15
10

Output:
5

PROGRAM FIBONACCI SERIES IN JAVA:

STATEMENT:

An integer value N is passed as the input. The program must print the first N terms in the Fibonacci sequence.


PROGRAM:

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();

        long prevTerm = 0,currentTerm = 1;

        int counter = 3;

        System.out.print(prevTerm+" "+currentTerm+" ");

                while (counter <= N) {

            System.out.print((prevTerm+currentTerm)+" ");

            currentTerm = prevTerm + currentTerm;

            prevTerm = currentTerm - prevTerm;

            counter++;
        }

    }
}

Input:
5

Output:
0 1 1 2 3

No comments:

Post a Comment