Go to Top

Friday 27 May 2011

To print the sum of the even numbers upto n in Java

Question 12 : Write a program in Java to compute the sum of the even numbers upto n terms using the for loop.


Java Program : 


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

Output : 

When n=15;

Sum : 240

Note : Use the same procedure to print the sum of odd numbers upto n terms.
Note : Use the calculator and the notepad provided, at the top, to dry run the program.

11 comments:

  1. write a program to display 100 prime numbers

    ReplyDelete
    Replies
    1. class sudhi1{
      public static void main(String args[]){
      int i,j,k;
      for(i=0;i<=100;i=i+1){
      k=0;
      for(j=2;j<i;j=j+1){
      if(i%j==0){
      k=1;break;
      }
      }
      if(k==0){
      System.out.println(i);
      }

      }

      }
      }

      Delete
    2. This comment has been removed by the author.

      Delete
  2. write a program to display 100 prime numbers

    ReplyDelete
    Replies
    1. class sudhi1{
      public static void main(String args[]){
      int i,j,k;
      for(i=0;i<=100;i=i+1){
      k=0;
      for(j=2;j<i;j=j+1){
      if(i%j==0){
      k=1;break;
      }
      }
      if(k==0){
      System.out.println(i);
      }

      }

      }
      }

      Delete
  3. 1
    3 1
    5 3 1
    7 5 3 1
    9 7 5 3 1
    Please solve it out fr me

    ReplyDelete
  4. i have the same model program
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    if need i will send it to you because i dont have time to create a new one><<<<<<<<<<<<,,,,,,,,,,,,,,,,<,.,,.

    ReplyDelete
  5. i have the same model program
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    if need i will send it to you because i dont have time to create a new one><<<<<<<<<<<<,,,,,,,,,,,,,,,,<,.,,.

    ReplyDelete
  6. Wap to print the following pattern
    school
    schoo
    scho
    sch
    sc
    s
    Plz reply

    ReplyDelete
  7. Wap to accept a no. And calculate the sum of even and odd digits separately.

    ReplyDelete
  8. BLUEJ
    LUEJB
    UEJBL
    EJBLU
    JBLUE
    how to print this pattern?

    ReplyDelete

ShareThis