user3081689
user3081689

Reputation: 31

Program that reads num and prints from 1 to num

i need help in logic, i need the program to read an integer from user and then prints all the integers from 1 to num1. here's what i got :

 import java.util.Scanner;

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

        Scanner scan = new Scanner(System.in);

        int num1;
        int num2;

        System.out.println("Enter any number:");
        num1 = scan.nextInt();

    while (num1<=num2) {    

        System.out.println(num+1);
    }
     }
    }

Upvotes: 1

Views: 142

Answers (4)

user3081689
user3081689

Reputation: 31

thanks alot guys! its been couple of years since last i coded a java program so im a little rusty! here's my final code :

import java.util.Scanner;

public class test
{
    public static void main (String[] args) 
    {
        Scanner scan = new Scanner(System.in);

        int num;
        int a=1;

        System.out.println("Enter any number:");
        num=scan.nextInt();

    while (a<=num)  
    {

        System.out.println(a);
        a++;}

    }}

Upvotes: 0

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try this out:

import java.util.Scanner;
    class test {
        public static void main(String[] args) {

            Scanner scan = new Scanner(System.in);

            int number;

            System.out.println("Enter any number:");
             // Note : The below statement will fail if user does not enter integer value
            number = scan.nextInt();

            // You can use while loop as well but for loop provides cleaner approach for iteration
            for (int i = 1; i <= number; i++) {
                // Print numbers sequentially from 1 to number
                System.out.println(i);
            }
        }
    }

Upvotes: 3

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

do like this

  int num1=0;
  int num2=0;
  System.out.println("Enter any number:");
  num1 = scan.nextInt();
  while (num2 <= num1) {    
       System.out.println(num2);
       num2++;
  } 

Upvotes: 0

Masudul
Masudul

Reputation: 21961

Program that reads num and prints from 1 to num

Try,

 System.out.println("Enter any number:");
 num1 = scan.nextInt();
 int i=1;
 while (i<=num1) {    
    System.out.println(i);
    i++;
 }

Upvotes: 0

Related Questions