Go to Top

Friday, 27 May 2011

To print the sum of the first ten even numbers in Java

Question 10 : Write a program in Java to compute the sum of the first ten even numbers using the for loop.


Java Program : 


class sum_even
{
 public static void main()
 {
     int s=0,i,c=0;
     for(i=1;;i++)
    {
      if(i%2==0)
      {
        s=s+i;
        c=c+1;
     }
     if(c==10)
     break;
    }
     System.out.print("Sum : "+s);
    }
}

Output : 


Sum : 110

Note : Use the calculator and the notepad provided, at the top, to dry run the program.

5 comments:

  1. arey bhayya yaha pein tho main function ka args array miss hogaya hain change it

    ReplyDelete
  2. Main args is not necessary. The program will still work if args is not given. The args[] is an array, and if I pass an array as parameter and don't use it, then why am I going to waste any amount of memory ?

    In other simple words, args is not necessary. You can still run the program without args. Try it by copying and pasting the program.

    ReplyDelete
    Replies
    1. but without args[] will it work even in command prompt?

      Delete
    2. yes it will

      Delete
  3. What changes are required if I want to print the squares of first 10 even numbers?

    ReplyDelete

ShareThis