In this post, we will write a two java program to find the cube of the numbers upto given an integer using For Loop and While Loop. Program will find the cude of first N number using for loop and while loop.
To understand these programs you should have knowledge of following concepts.
- For Loop
- While Loop
How the program will work?
- First of all, we will accept the number from user.
- Now using loop we will calculate the cube of first numbers.
Example:
- Input:
- Enter the number: 6
- Output:
- Number is : 1 and cube of 1 is : 1
- Number is : 2 and cube of 2 is : 8
- Number is : 3 and cube of 3 is : 27
- Number is : 4 and cube of 4 is : 64
- Number is : 5 and cube of 5 is : 125
- Number is : 6 and cube of 6 is : 216
Example 1: Program to Find cube of a first N Number using For Loop
This Java program enable the user to enter an integer value. Then this java program will calculates cube of the First N number and display. To do this program is going to use for loop.
import java.util.Scanner; public class cube_of_n_numbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number: "); int num = sc.nextInt(); for (int i=1;i<=num;i++){ System.out.println("Number is : "+i+" and cube of "+i+" is : "+(i*i*i)); } } }
Output:
Enter the number: 5 Number is : 1 and cube of 1 is : 1 Number is : 2 and cube of 2 is : 8 Number is : 3 and cube of 3 is : 27 Number is : 4 and cube of 4 is : 64 Number is : 5 and cube of 5 is : 125
Example 2: Program to Find cube of a first N Number using while loop
This Java Program is same as above. But this time, we are creating a different technique to calculate the cube of the first N number. This java program using while Loop to calculate the cube.
import java.util.Scanner; public class cube_of_n_numbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number: "); int num = sc.nextInt(); int i=1; while (i<=num){ System.out.println("Number is : "+i+" and cube of "+i+" is : "+(i*i*i)); i++; } } }
Output:
Enter the number: 7 Number is : 1 and cube of 1 is : 1 Number is : 2 and cube of 2 is : 8 Number is : 3 and cube of 3 is : 27 Number is : 4 and cube of 4 is : 64 Number is : 5 and cube of 5 is : 125 Number is : 6 and cube of 6 is : 216 Number is : 7 and cube of 7 is : 343
Recommended:
- Java Program to find the greatest of three Numbers
- Java Program to Display the weekday between 1 and 7
- Java Program to Find the number of days in a Months.
- Java Program to Print character is vowel or Consonant
- Java Program to Check a year is a leap year or not
- Java Program to display the sum of first N natural numbers
- Java Program to find sum and average of N numbers