Help using a For Structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DaveoB
    New Member
    • Nov 2007
    • 2

    #1

    Help using a For Structure

    Hey

    Im wonderin if anyone can help me with this question,Sum the odd numbers between 1 and 97, using a for structure. Might seem a bit simple but i cant get it to work. Anyone help?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by DaveoB
    Hey

    Im wonderin if anyone can help me with this question,Sum the odd numbers between 1 and 97, using a for structure. Might seem a bit simple but i cant get it to work. Anyone help?
    So you have to do this: sum(i= 1 ... 97 | i where i odd)

    In Java that translates to something like this:

    [code=java]
    int sum= 0;
    for (int i= 1; i <= 97; i++)
    if (odd(i)) // add i to sum
    [/code]

    But you can do better than that and get rid of that odd(i) predicate altogether:

    [code=java]
    int sum= 0;
    for (int i= 1; i <= 97; i+= 2)
    // add i to sum
    [/code]

    kind regards,

    Jos

    Comment

    • DaveoB
      New Member
      • Nov 2007
      • 2

      #3
      This is what i've done and it's throwing up 43 errors. ne ideas?

      public class Project_1_0
      {
      public static void main(String[] args)
      {



      for (int i= 1; i <= 97; i+= 2)
      {

      System.out.prin t(i);
      System.out.prin t(" ");
      }

      }

      }

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by DaveoB
        This is what i've done and it's throwing up 43 errors. ne ideas?

        public class Project_1_0
        {
        public static void main(String[] args)
        {



        for (int i= 1; i <= 97; i+= 2)
        {

        System.out.prin t(i);
        System.out.prin t(" ");
        }

        }

        }
        1.) Use code tags when posting code (like Jos did above)
        2.) What are the errors you are getting?

        Comment

        Working...