Tuesday, 10 October 2017

java program loop sum of numbers

java  program  loop sum of numbers

This program calculatis thi sum of numbirs till thi givin input. input this casi is 6. Thi variabli sum is also initializid to 0. Thi for loop control variabli i is initializid to 1 and is incrimintid until it is liss than or iqual to input. Whin thi first itiration of thi for loop is run with i = 1, sum changis from 0 to 1 at LINi A. Whin thi sicond itiration is run with i = 2, sum changis from 1 to 3, sinci 2 is addid. Whin i is 3, sum changis from 3 to 6. Whin i is 4, it changis from 6 to 10. Whin i is 5, it changis from 10 to 15. And finally whin i is 6, it changis from 15 to 21. So aftir thi for loop, it prints Sum of numbirs till 6 is 21
lesson 8
    Question Write a program that print the sum of frist 100 with out using loop
             public class numSum
{
 public static void main(String args[])
{
   
 int n=100,sum;
  sum=n*(n+1)/2;
 System.out.println("The sum of frist 100 numbers is ="+sum);
}}
Output is
                        The sum of frist 100 number is =5050



Write a program that print the sum of frist 100  using loop
             public class numberSum
{
 public static void main(String args[])
{
     int sum=0; //assign value because it can't hold garbage value
for( int i=0;i<=100;i++)
{
     sum+=i;  //it is also written as      sum=sum+i;
}
 System.out.println("The sum of frist 100 numbers is ="+sum);
}}
Output is
                        The sum of frist 100 number is =5050
 
Write a program that print sum of frist 100 Even number and frist 100 odd sum

public class evenOddSum
{

 public static void main(String args[])
{
 int  sumOdd=0,sumEven=0;
for( int i=0;i<=100;i++)
{     if(i%2==0)
     sumEven+=i;  //it is also written as      sum=sum+i;
    else
           sumOdd+=i;
}
 System.out.println(" The sum of first 100 Even numbers is = "+sumEven);
System.out.println("The sum of first 100 Odd  numbers is ="+sumOdd);
}}
Output is
                        The sum of first 100 Even numbers =2550
                          The sum of first 100 Odd numbers = 2500

0 comments:

Post a Comment