Results 1 to 3 of 3

Thread: While Loop Java?

  1. #1
    Join Date
    Jan 2008
    Posts
    1

    Default While Loop Java?

    I need to write a program that will find all numbers 1 to "n:"

    "n" is a value the user inputs
    Sorry everyone those were all great answers. but, the program adds all numbers 1 to n

    Sorry i forgot to put thar
    Powered by Yahoo!

  2. #2
    Join Date
    Jan 2008
    Posts
    1

    Default

    import java.io.*;

    public class AllNumbers
    {
    private static BufferedReader var = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[]args)throws IOException
    {
    System.out.println("Enter value for n: ");
    String str = var.readLine();
    int datum = Integer.parseInt(str);
    for(int x = 1; x <= datum; x++)
    {
    System.out.println(x + " ");
    }
    }
    }
    Powered by Yahoo!

  3. #3

    Default

    now it's in while loop:

    import java.io.*;
    class Numbers
    {
    public static void main(String args[ ]) throws IOException
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int i=1,n,S=0;
    System.out.print("Enter the value of n ");
    String a=br.readLine();
    n=Integer.parseInt(a);
    while(i<=n)
    {
    S=S+i;
    i++;
    }
    System.out.print("Sum= "+S);
    }
    }
    int i,n,S=0;
    System.out.print("Enter the value of n ");
    String a=br.readLine();
    n=Integer.parseInt(a);
    for(i=1;i<=n;i++)
    {
    S=S+i;
    }
    System.out.print("Sum= "+S);
    }
    }
    Powered by Yahoo!

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •