Search This Blog

UI/UX Design | Web Development | Mobile Application Development

Whether you need UI/ UX design, web development services, or mobile app development services, Qaabil Digitals will be more than happy to help you. We work with top software developers, designers, and project managers. We tailor our services to suit your exact needs. We closely look at your company, listen to your story, and bring about the best ideas and solutions that can help you drive solid results. We don’t just produce work that works. We produce work that matters. Get a quote now Or Talk to us

Tuesday, 5 July 2011

Write a program to print factorial of any number


import java.util.*;
class factorial
{
public static void main (String arg[])
{
Scanner in = new Scanner (System.in);

int a,b=1;
System.out.print ("\n\t Enter the number = ");
a=in.nextInt();

while (a>0)
{
b*=a;
--a;
}

System.out.println ("\n\t Factorial = "+b);

}
}

Note:
     First of all computer will check the condition of while loop. If it is true then it will
 multiply b by a. After that it will decrease the value of a by 1 and repeat the same task. This
 will continue until a=0. When a=0 the loop will be broken and the next statement to it will
be executed.

Write a program that print all odd numbers from 0 to a user specific number using do while loop


import java.util.*;
class odd
{
public static void main (String arg[])
{
Scanner in = new Scanner (System.in);
int a;
System.out.print ("\n\t Enter the ending number = ");
a=in.nextInt();
 
do
{
if (a%2!=0)
System.out.print ("\n\t "+a);
--a;
}while (a>0);

}
}

Note:
        In this program if we divide a by 2 and it do not returns 0, then it will be printed on
screen otherwise not.

Write a program to calculate sum and product of even numbers


import java.util.*;
class sumeven
{
public static void main (String arg[])
{
Scanner in = new Scanner (System.in);
int a,s=0,p=1;
System.out.print ("\n\t Enter the ending number = ");
a=in.nextInt();

while (a>0)
{
if (a%2==0)
{
s+=a;
p*=a;
}
--a;
}

System.out.println ("\n\t Sum of even numbers = "+s);
System.out.println ("\n\t Product of even numbers = "+p);
}
}

Note:
         In this program we have used two arithmetic operators in the body of if statement. First
is adding, whatever the value of a, in s and second is multiplying all values of a.

Write a program that print all even numbers from 0 to a given range


import java.util.*;
class even
{
public static void main (String arg[])
{
int a;
System.out.print ("\n\t Enter the number = ");
a=in.nextInt();

while (a>0)
{
if (a%2==0)
System.out.print ("\n\t "+a);
--a;
}

}
}

Note:
         In this program, body of the loop will be executed till a is greater than 0. As you have
noticed a conditional statement in the body of the loop, this is the actual code in our program
which is checking that either the number is even or odd.

Share