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++;
};
}
}
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.
@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?
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.