While Loop Program

Hello Java Beginner,

Now we work on while loop program with some important tips. “While loop” is same as for loop. We can also call entry control loop.

Let’s some program on while loop program.

 

First Program is on “Sum of digit”.

While Loop Program: “Sum of Digit”

Enter Number: 12345 [Find sum of 1+2+3+4+5 = 15]

 class loop4

{

public static void main(String args[])

{

int i;

int n = Integer.parseInt(args[0]);

int digit;

int sum = 0;

while(n>0)

{

digit = n%10;       // 12345%10 => 5

sum = sum + digit; // 5 = 0 + 5

n/=10;                             // 12345/10 => 1234

}

System.out.println(“Sum = “ +sum);

}

}

Output:

Command line Value is: 12345

 Sum = 15

 

Second Program is on “Find Number is Magic or Not”.

Program on While Loop.

class loop5

{

public static void main(String args[])

{

int n = Integer.parseInt(args[0]);

int sum = 0,mul=1,digit,i;

while(n>0)

{

digit = n%10;

sum = sum + digit;

mul = mul*digit;

n/=10;

}

if(mul == sum)

{

System.out.println(“MAgic number”);

}

else

{

System.out.println(“Not MAgic number”);

}

}

}

Output:

Command line Value is: 123

Magic Number [Because 1+2+3 == 1*2*3]

Command Line Value is: 124

Not Magic Number [Because 1+2+4 != 1*2*4]

 

This program will help you to understand basic structure of while loop. You can also try this program in “for and do..while loop”.

List Of Tutorial on For, While and Do..while Loop.

NoTitle
1Enter Number [Find number is amstrong or Not]
2Find sum of odd digit from number.
3Enter Number [Find Reverse Number]
4Enter Number [Find number is palimdrom or not]

 

If you have problem on this blog, you can directly comment on it.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

297total visits,4visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image

EmailEmail
PrintPrint