Programmator
Programmator
  • Home
  • Download
  • Social
    • YouTube
    • Instagram
    • Facebook
    • Telegram
  • Features
    • C/C++
    • Java
      • Category 1
      • Category 2
      • Category 3
      • Category 4
      • Category 5
    • Sub Menu 3
    • Sub Menu 4
  • Contact Us

Count number of digits in an integer using while loop

We can count the number of digits in a given number in many ways using java.

One of the approach is that, we shall take the number, remove the last digit, and increment our counter for number of digits in the number. We can continue this, until there is no digit in the number.

Another approach is that, we can convert the given number into a string, and use the method string.length() to count the number of character in this string. This results in the number of digits in given number.

Here, while the loop is iterated until the test expression number != 0 is evaluated to 0(false).

After the first iteration, number will be divided by 10 and its value will be 345. Then, the count is incremented to 1.

After the second iteration, the value of number will be 34 and the count is increased to 2.

After the third iteration, the value of number will be 3 and the count is increased to 3.

After the fourth iteration, the value of number will be 0 and the count is increased to 4.

Then the test expression is evaluated to false and the loop terminates.

  • Program:

public class Main {

  public static void main(String[] args) {

    int count = 0, number = 0003452;

    while (number != 0) {
      // number = number/10
      number /= 10;
      ++count;
    }

    System.out.println("Number of digits: " + count);
  }
}

  • Output:

Number of digits: 4

Write a java program to display alphabets (A to Z) using loop

In this program, we can loop through A to Z using for loop because they are stored as ASCII characters in java.

This java program iterates the ASCII code from 65 to 90, representing the alphabets A to Z and print them.

With a little modification you can display lowercase alphabets to simply replace the A with a and Z with z. In this case, internally your loop through 97 to 122.

  • Program:

class Main {
  public static void main(String[] args) {

    char n;

    for(n = 'A'; n <= 'Z'; ++n) // For lowercase: for(n = 'a'; n <= 'b'; ++n)
      System.out.print(n + " ");
    }
}

  • Output:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 


Java program to find LCM of two numbers

In this program, LCM(Least common multiple) of two or more numbers is the least positive number that can be divided by both the numbers, without leaving the remainder. It is also known as Lowest common multiple, Least Common Denominator and smallest common multiple. It is denoted by LCM (a, b) or lcm (a, b) where a and b are two integers.

It is used when we add, subtract, or compare the fractions. While we perform addition or subtraction of the fractions, we find the LCM of the denominators and then solve the fraction. The LCM of the denominator is known as the Least Common Denominator (LCD).

  • Program:

public class Main {
    public static void main(String[] args) {

        int a = 72, b = 120, lcm;

        // maximum number between a and b is stored in lcm
        lcm = (a > b) ? a : b;
        while(true) {
            if( lcm % a == 0 && lcm % b == 0 ) {
                System.out.printf("The LCM of %d and %d is %d.", a, b, lcm);
                break;
            }
            ++lcm;
        }
    }
}

  • Output:

The LCM of 72 and 120 is 360.

In this program, we have covered different logic in java programs to find GCD of two numbers.

We have initialized two numbers n1=11 and n2=102. After that, we have used a for loop that runs from 1 to the smallest of both numbers. It executes until the condition i<=n1 && i<=n2 returns true. Inside the for loop, we have also used if statement that tests the condition (n1%i== && n2%i==0) and returns true if both conditions are satisfied. At last, we have stored the value of i in the variable gcd and print the same gcd variable.

  • Program:

class Main {
  public static void main(String[] args) {
    
    int n1 = 11, n2 = 102; // find GCD between n1 and n2
   
    int gcd = 1; // initially set to gcd

    for (int i = 1; i <= n1 && i <= n2; ++i) {
   
      if (n1 % i == 0 && n2 % i == 0) // check if i perfectly divides both n1 and n2
        gcd = i;
    }

    System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);
  }
}

  • Output:

GCD of 11 and 102 is 1

Write a java program to display Fibonacci series

In this program, Fibonacci series means to next number is the sum previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of Fibonacci series are 0 and 1.

There are two ways to write the Fibonacci series program in java:

  1. Fibonacci series without using recursion
  2. Fibonacci series using recursion

  • Program:

class Main {
  public static void main(String[] args) {

    int n = 10, firstTerm = 0, secondTerm = 1;
    System.out.println("Fibonacci Series till " + n + " terms:");

    for (int i = 1; i <= n; ++i) {
      System.out.print(firstTerm + ", ");

      // compute the next term
      int nextTerm = firstTerm + secondTerm;
      firstTerm = secondTerm;
      secondTerm = nextTerm;
    }
  }
}

  • Output:

Fibonacci Series till 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,



How to generate multiplication table in java?

In this program, we will understand the logic to print table and also implement that logic in java programs.

A table is a sequence of number that are generated using multiplication. We enter an integer as input of which we want to print the table. After that, we multiply the entered by 1 to 10, respectively on by one.

Suppose we have entered 5 as input then the table of 5 will be:

5*1 = 5
5*2= 10
5*3 =15

  • Program:

public class MultiplicationTable {

    public static void main(String[] args) {

        int num = 8;
        for(int i = 1; i <= 10; ++i)
        {
            System.out.printf("%d * %d = %d \n", num, i, num * i);
        }
    }
}

  • Output:

8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80



Write a java program to find factorial of a number

Here, we will used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.

We will used long instead of int to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable in java.math library.

  • Program:

import java.math.BigInteger;

public class Factorial {

    public static void main(String[] args) {

        int num = 11;
        BigInteger factorial = BigInteger.ONE;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

Output:

Factorial of 11 = 39916800

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 

Write a java program to calculate the sum of natural numbers using for loop

The natural numbers are the numbers that include all the positive integers from 1 to infinity. For example, 1, 2, 3, 4, 5, ...., n. When we add these numbers together, we get the sum of natural numbers.

In this section, we will create the following programs:

  • Java program to find the sum of the first 100 natural numbers
  • Java program to find the sum of n natural numbers
  • Java program to find the sum of n natural numbers using the function

We can also find the sum of n natural number using the mathematical formula:

Sum of n natural numbers = n*(n+1)/2

Suppose we want to find the sum of the 100 natural numbers. By putting the value in the above formula, we get:

Sum = 100*100+1/2 = 100*50.5 = 5050

Here, we are going to use for loop to find the sum of natural numbers.

  • Program:

public class SumNatural {

    public static void main(String[] args) {

        int num = 110, sum = 0;

        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

  • Output:

Sum = 6105

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 

Write a java program to check whether a character is alphabet or not

Here, the char variable stores the ASCII value of a character (number between 0 and 127) rather than the character itself.

The ASCII value of lowercase alphabets are from 97 to 122. And the ASCII value of uppercase alphabets are from 65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122. similarly, alphabet A is stored as 65 and alphabet Z is stored as 90.

Now, when we compare variable c between 'a' to 'z' and 'A' to 'Z', the variable is compared with the ASCII value of the alphabets 97 to 122 and 65 to 90 respectively.

since the ASCII value of * does not fall in between the ASCII value of alphabets. Hence, the program outputs * is not an alphabet.

  • Program:

public class Alphabet {

    public static void main(String[] args) {

        char c = '-';

        if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            System.out.println(c + " is an alphabet.");
        else
            System.out.println(c + " is not an alphabet.");
    }
}

  • Output:

- is not an alphabet.

----- OR -----

n is an alphabet.

----- OR -----

V is an alphabet.
 
  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here

Write a java program to check if number is positive or negative

Here, we will write java program to checks whether the specified number is positive or negative using the if else statements.

  • If a number is less than zero, then it is a negative number
  • If a number is greater than zero, then it is a negative number
  • If a number is equal to zero, then it is neither negative nor positive number

  • Program:

public class PositiveNegative {

    public static void main(String[] args) {

        double number = 11.1;

        // true if number is less than 0
        if (number < 0.0)
            System.out.println(number + " is a negative number.");

        // true if number is greater than 0
        else if ( number > 0.0)
            System.out.println(number + " is a positive number.");

        // if both test expression is evaluated to false
        else
            System.out.println(number + " is 0.");
    }
}

  • Output:


11.1 is a positive number.

----- OR -----

-11.1 is a negative number.

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here

Java program to multiply two floating point numbers

In the below program, we have two floating - point numbers 3.4f and 1.5f stored in variables first and second respectively.

Notice, we have used f after the numbers. This ensures the numbers are float, otherwise they will be assigned typed double.

first and second are then multiplied using the * operator and the result is stored in a new float variable product.

Finally, the result product is printed on the screen using println() function.

  • Program:

public class MultiplyTwoNumbers {

    public static void main(String[] args) {

        float first = 3.4f;
        float second = 1.5f;

        float product = first * second;

        System.out.println("The product is: " + product);
    }
}

  • Output:

The product is: 5.1

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here

Write a java program to check leap year

Leap year contains 366 days, which comes once every four years.
Every leap year corresponds to these facts:

  • A century year is a year ending with 00.  A century year is a leap year only if it is divisible by 400.
  • A leap year (except a century year) can be identified if it is exactly divisible by 4.
  • A century year should be divisible by 4 and 100 both.
  • A non-century year should be divisible only by 4.

Let's find out whether a year is a leap year or not

  • Program:

public class Main {

  public static void main(String[] args) {

    // year to be checked
    int year = 2011;
    boolean leap = false;

    // if the year is divided by 4
    if (year % 4 == 0) {

      // if the year is century
      if (year % 100 == 0) {

        // if year is divided by 400
        // then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      
      // if the year is not century
      else
        leap = true;
    }
    
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
  }
}

  • Output:

2011 is not a leap year

--- Another example ---

2012 is a leap year

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here

Write a java program to find all roots of a quadratic equation

The standard form of an equation is:
ax2+bx+c=0

Here, a, b and c are real numbers and a can't be equal to 0.

We can calculate the root of a quadratic by using the formula

x=−b±b2−4ac−−−−−−−√2a

The ± sign indicates that there will be two roots:

root1=−b +b2−4ac−−−−−−−√2a

root2=−b -b2−4ac−−−−−−−√2a

The term b2-4ac is known as the determinant of a quadratic equation. It specifies the nature of roots. That is,

  • if determinant > 0, roots are real and different
  • if determinant < 0, roots are complex and different
  • if determinant == 0, roots are real and equal

  • Program:

public class Main {

  public static void main(String[] args) {

    // value a, b, and c
    double a = 4.6, b = 2, c = 4.2;
    double root1, root2;

    // calculate the determinant (b2 - 4ac)
    double determinant = b * b - 4 * a * c;

    // check if determinant is greater than 0
    if (determinant > 0) {

      // two real and distinct roots
      root1 = (-b + Math.sqrt(determinant)) / (2 * a);
      root2 = (-b - Math.sqrt(determinant)) / (2 * a);

      System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
    }

    // check if determinant is equal to 0
    else if (determinant == 0) {

      // two real and equal roots
      // determinant is equal to 0
      // so -b + 0 == -b
      root1 = root2 = -b / (2 * a);
      System.out.format("root1 = root2 = %.2f;", root1);
    }

    // if determinant is less than zero
    else {

      // roots are complex number and distinct
      double real = -b / (2 * a);
      double imaginary = Math.sqrt(-determinant) / (2 * a);
      System.out.format("root1 = %.2f+%.2fi", real, imaginary);
      System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
    }
  }
}

  • Output:

root1 = -0.22+0.93i
root2 = -0.22-0.93i

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here
Newer Posts Older Posts Home

ABOUT

I could look back at my life and get a good story out of it. It's a picture of somebody trying to figure things out.

SUBSCRIBE & FOLLOW

POPULAR POSTS

  • Java program to check whether a given number is even or odd
  • Java program to find factorial of a number
  • Write a java program to multiply two floating point numbers
  • Java program to find the largest among three numbers
  • java program to calculate the sum of natural numbers

Advertisement

👆 Shopping 👆

Powered by Blogger

Archive

  • January 20231
  • December 20223
  • November 202215
  • August 20222

Report Abuse

Copyright

  • Home
  • About US
  • Privacy Policy
  • Disclaimer

About Me

Nilesh Patel
View my complete profile

Copyright © Programmator. Designed by OddThemes