# Basic Loops 3

No one can now stop you from mastering loops!

## Program1: Write a java program to input a number from user and check whether given number is Armstrong number or not.

An Armstrong number is a n-digit number that is equal to the sum of the n^{th} power of its digits. For example –

6 = 6^{1} = 6

371 = 3^{3} + 7^{3} + 1^{3} = 371

### Input

`371`

### Output

`371 is armstrong number`

### Approach

## Hint

In the previous article we have covered how to calculate number of digits of a number, how to get hold of the digits and also, how to calculate the power of a number to some exponent.

So, firstly calculate the number of digits. Then one by one get the digits and calculate the power of the digit with exponent as total number of digits. And update the sum. Finally check whether the number is armstrong or not. by equating the sum with the number.

## Solution

```
import java.util.*;
public class main {
public static void main(String[] args) {
// Input number from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter any number to check Armstrong number: ");
int num = scanner.nextInt();
int sum = 0;
// Copy the value of num for processing
int originalNum = num;
// Find total digits in num
int digits = (int) Math.log10(num) + 1;
// Calculate sum of power of digits
while (num > 0) {
// Extract the last digit
int lastDigit = num % 10;
// Compute sum of power of last digit
sum = sum + (int) Math.pow(lastDigit, digits);
// Remove the last digit
num = num / 10;
}
// Check for Armstrong number
if (originalNum == sum) {
System.out.println(originalNum + " is ARMSTRONG NUMBER");
} else {
System.out.println(originalNum + " is NOT ARMSTRONG NUMBER");
}
}
}
```

## Program2: Write a java program to find all Perfect numbers in a given range.

Perfect number is a positive integer which is equal to the sum of its proper positive divisors.

For example: 6 is the first perfect number

Proper divisors of 6 are 1, 2, 3

Sum of its proper divisors = 1 + 2 + 3 = 6.

Hence 6 is a perfect number.

### Input

```
Lower limit: 1
Upper limit: 100
```

### Output

`6, 28`

### Approach

## Hint

You remember the concept of calculating factors of a number. We can use the same to get the positive proper divisors of the number and then, calculate their sum. If the sum equals the number, it is perfect else not.

And get all the perfect numbers in the range, we can loop around them and check.

## Solution

```
import java.util.*;
public class main {
public static void main(String[] args) {
// Input lower and upper limit from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter lower limit: ");
int start = scanner.nextInt();
System.out.print("Enter upper limit: ");
int end = scanner.nextInt();
System.out.println("All Perfect numbers between " + start + " to " + end + ":");
// Iterate from start to end
for (int i = start; i <= end; i++) {
int sum = 0;
// Check whether the current number i is a Perfect number or not
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
// If the current number i is a Perfect number
if (sum == i) {
System.out.print(i + ", ");
}
}
}
}
```

## Program3: Write a java program to print Strong numbers between 1 to n.

Strong number is a special number whose sum of factorial of digits is equal to the original number.

For example: 145 is strong number. Since, 1! + 4! + 5! = 145,

### Input

`1000`

### Output

`1, 2, 145`

### Approach

## Hint

In the previous article we have covered how to get hold of each digit of a number and also, how to calculate the factorial of the a number. We can use the concept to check whether a number is strong or not.

## Solution

```
import java.util.*;
public class main {
public static void main(String[] args) {
// Input upper limit from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter upper limit: ");
int end = scanner.nextInt();
System.out.println("All Strong numbers between 1 to " + end + " are:");
// Iterate from 1 to end
for (int i = 1; i <= end; i++) {
// Number to check for a strong number
int cur = i;
long sum = 0;
// Find the sum of factorial of digits
while (cur > 0) {
long fact = 1L;
int lastDigit = cur % 10;
// Find factorial of the last digit of the current number
for (int j = 1; j <= lastDigit; j++) {
fact = fact * j;
}
sum += fact;
cur /= 10;
}
// Print 'i' if it is a strong number
if (sum == i) {
System.out.print(i + ", ");
}
}
}
}
```

Try coding for finding the strong numbers in a range specified by "start" and "end" as well.

**Program4: Write a java program to print Fibonacci series up to n terms using **loop**. **

Fibonacci series is a series of numbers where the current number is the sum of previous two terms. For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, … , (n-1th + n-2th)

### Input

`10`

### Output

`0, 1, 1, 2, 3, 5, 8, 13, 21, 34`

### Approach

## Hint

For getting the next number in the sequence, we can simply add the previous two numbers in the sequence. Loops can easily help us do that.

Initially we can store the value 0 and 1 in two variable. Then, we can iterate n times, calculate the sum of previous two numbers and update their value.

(To my surprise, my friend gave me a sunflower yesterday, and I noticed that the spirals in its head too follow the interesting Fibonacci series 🌻 )

## Solution

```
import java.util.*;
public class main {
public static void main(String[] args) {
// Input number of terms from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int terms = scanner.nextInt();
// Fibonacci magic initialization
int a = 0;
int b = 1;
int c = 0;
System.out.println("Fibonacci terms: ");
// Iterate through n terms
for (int i = 1; i <= terms; i++) {
System.out.print(c + ", ");
// Update variables for the next term
a = b; // Copy n-1 to n-2
b = c; // Copy current to n-1
c = a + b; // New term
}
}
}
```

## Program5: Write a java program to print pascal's triangle up to n rows using loop.

There are many definitions of Pascal's Triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown below.

Or Pascal's triangle is a triangular array of binomial coefficients.

### Input

`5`

### Output

```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```

### Approach

## Hint

Imagine you have a series of buckets arranged in rows as shown, and each bucket can hold a certain amount of water. The buckets are stacked in such a way that each row represents a level, and the buckets within each row are numbered.

If you carefully notice, the amount of water in bucket of zeroth row = C(0, 0) = 1

Similarly, 0th bucket of 1st row = C(1, 0) = 1 and 1st bucket = C(1, 1) = 1

Talking about 0th bucket of 2nd row = C(2, 0) = 1, 1st bucket = C(2, 1) = 2 and 2nd bucket = C(2, 2) = 1

An so on..

Clearly printing values of all rows require nested loops and we can use combinations to get amount of water held by a bucket.

Also, C(row, col) = row! / ( (row-col)! * col! )

## Solution

```
import java.util.*;
public class main {
// Function to calculate factorial
static long fact(int n) {
long factorial = 1L;
while (n >= 1) {
factorial *= n;
n--;
}
return factorial;
}
public static void main(String[] args) {
// Input number of rows
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.println();
for (int n = 0; n < rows; n++) {
// Prints spaces
for (int i = n; i < rows - 1; i++)
System.out.print(' ');
// Generate value for the current box
for (int k = 0; k <= n; k++) {
long value = fact(n) / (fact(k) * fact(n - k));
System.out.print(value + " ");
}
System.out.println();
}
}
}
```

**Time to pat your back for completing this article!Great going 🌟**