what is wrong in this code??(Life universe......program)

class Input1
{
public static void main(String args[])
{
int a[]={1,2,88,42,99};
int i=0;
while(a[i]!=42)
{
System.out.println(a[i]);
i++;
};
}
}

1 Like

I guess you are new to this platform. You don’t simply hardcode the sample input values into your code. You need to take input from stdin and print out your output there.

P.S: Your approach is the same as manually printing out 1,2,88.

1 Like

@philosophicalp your program is correct for the input 1 2 88 42 99. But, what happens if the input changes to 42 1 2 88 99. Don’t try to hardcore the input, read the input from the standard input stream.

P.S: Check some sample programs and try to find out where you go wrong.

import java.util.*;
class integers
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

while(true)
{
int a=sc.nextInt();
if(a==42)
break;
System.out.println(a);
}
}
}

this is the correct java code.

#include
using namespace std;
int main()
{
int i,a[10],k;
cout<<“Enter the five numbers\n”;
for(i=0;i<5;i++)
{
cin>>a[i];
}
for(i=0;i<5;i++)
{
if(a[i]!=42)
{
cout<<a[i]<<"\n";
}
else
{
break;
}
}
return 0;
}
What’s wrong in this?

@rahurl,

You should take input only what is required and not print unnecessary lines such as “Enter the five numbers”. Also the given problem does not specify that only five numbers would be tested. It asks you to take numbers as input and print them indefinitely until the number 42 is encountered. So you should prefer to use a ‘while’ loop here rather than a ‘for’ loop.