Why for loop is behaving differently? - java

Here I am trying to reverse a number using for loop but when n=1234 it gives the output 432 only.
Please explain why for loop behaving differently.
When i tried the same problem with while loop using condition while(n>0) it worked as expected and gave the desired output
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int rev=0;
for(int i=1;i<=n;i++){
int temp=n%10;
n=n/10;
rev=rev*10+temp;
}
System.out.println(rev);
expected output is 4321 when n=1234 but it is giving output as 432

Its seems like you need to read more about loops in java
when you use for loop, you go thru all the numbers from 1 (in your case) to n
and when you use while you go until n is 0
you can see there is a different between the values you end up with, i really suggesting you to watch some more toturials before moving on :)

Understand what you want to achieve first: For reversing a number
Input: num
(1) Initialize reverse_num = 0
(2) Loop while num > 0
(a) Multiply reverse_num by 10 and add remainder of num
divide by 10 to rev_num
reverse_num = reverse_num*10 + num%10;
(b) Divide num by 10
(3) print reverse_num
The for loop you are using is taking all the values in consideration starting from 1 to 1234 (1, 2, 3, 4,5, 6......1234)
When you are using while loop you just have one condition if num>0 which is what we need, hence it works.
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int reversed = 0;
while(num >0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println(reversed);
}

Try smth like this:
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int rev=0;
while(n>0)
{
int temp=n%10;
rev=rev*10+temp;
n=n/10;
}
System.out.println(rev);
Will be better to use while

How the algorithm work with while and why you need to cut untill n=0(1234 as example):while(do this untill n == 0).
First try:
first line:temp=n%10 so temp=1234%10=4.second line:n=n/10 so n=1234/10=123
third line: rev=rev*10+temp so 0*10+4=4;
Next try:
first line:temp=n%10 so temp=123%10=3,second line:n=n/10 so n=123/10=12,
third line: rev=rev*10+temp so 4*10+3=43;
Next try:
first line:temp=n%10 so temp=12%10=2 second line:n=n/10 so n=12/10=1.2(1,int)
third line:rev=rev*10+temp so 43*10+2=432;
Final try:
first line:temp=n%10 so temp=1%10=1
second line:n=n/10 so n=1/10=0.1(0,int),third line: rev=rev*10+temp so REV it's 432*10+1=4321;

Related

Printing Fibonacci series between 1-99

The program listed is about writing the Fibonacci series given user input that is below 100. The problem that I am having is figuring out how to get the Fibonacci to not print if the number listed by the user is above 100. However, I am unable to figure out what to do. This is my code, I am not trying to use while loop to only print if the number is between 1 and 100. however when I print 101, it still gives me the Fibonacci series.
import java.util.Scanner;
class Program_2 {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer between 1-99: ");
int num = console.nextInt();
while (num>1) {
if(num<100) {
System.out.println("Fibonacci Series till " + num + " terms:");
}
int n = 100, firstTerm = 0, secondTerm = 1;
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + ", ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
}
The Output that im getting when i print 101, is
I've used an if/else statement, but for some reason, it didnt do anything. Then I tried using a while loop and an if statement, but its still printing above 100. I am unsure how to go about this. Any help is very much appreciated!
To fix this issue, you can add another condition into your while loop. Right now, you are going into the while loop as long as num is greater than 1. Thus, numbers above 100 are being considered as well. To fix this, you can make your while loop start like this: while(num>1 && num<=100).
Your while check "while(n>1)" will run infinitely. You need to change num's value after every iteration like this:
num--; //In the loop
And when num becomes less than 1, the program exits from the loop.
If you want to check whether num is less than 100 or bigger than 1 use if statement(to check if input value corresponds to your range)
while(num > 1 && num < 100){
//your code in while loop
}else{
System.out.println("Your value is too big or too small!");
}
And also I've noticed your output of fibonacci sequence is not right(negative values, bound in int32). You can't even display in long values because fibonacci of 9*th order are over quadrillions. Try to use BigInteger in order to show right values in the console output. Want to fancy your output? Use /t and %n in System.out.print();

how to output answer after each input using a loop?

If I wanted to enter 10 numbers, and after each number it displays the square root, how would I do this using a for loop?
int number;
System.out.print("Enter a number: ");
num = input.nextInt();
for (count = 0; count <= 10; count++)
{
System.out.println("The Square of Number is : "+(num*num));
System.out.println("The Cube of Number is : "+(num*num*num));
I have tried this code. However, it displays 1 input 10 times. How do I get it to display after each input?
Similar to what others have said, you are only getting input once, and then printing the output 10 times. input.nextInt() must be moved inside the for loop.
However, something that hasn't been said is that you aren't consuming the newline delimeter. (Assuming you're using the console, which it seems you are) When the user inputs text by hitting enter, there is a newline delimeter at the end of the input. You are only consuming the number, but not the newline.
An example of this can be found here.
If you want to output the square root after you entered a number, just put num = input.nextInt(); inside the for-loop, as already mentioned.
If you however want to input the 10 numbers first and then output the squares of every number, this would be a pretty good solution:
int[] numbers = new int[10];
for(int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt();
for(int tempInt : numbers) System.out.println(Math.pow(tempInt, 2));
Move num = input.nextInt() inside the for loop, like #Pavneet Singh said. If you want it to display all 10 after they have been entered, use an int[] with a length of 10 like this:
int[] numbers = new int[10];

Output for finding Sum of the subarray do not come as Expected

Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts are given in the array Value where ith friend asks for a gift which has a cost Costi.
But, Prateek has only X amount of money to spend on gifts and he wants to invite his friends which are in continuous range such that sum of the cost of the gifts of those friends will be exactly equal to X.
If he can invite his friends, who can satisfy the above condition then, print YES otherwise print NO.
Input:
The first line contains a single integer T, denoting the number of test cases. In each test case, the following input will be present: - The next line contains two space-separated integers N and X, where N represents the number of friends and X represents amount of money which Prateek can spend on gifts.
- Next N line contains N integers, where ith line contains ith integer, which represents the Costi .
Ouput
Output exactly T lines, each containing the answer to the corresponding test case .
Constraints:
1 <= T <= 10
1 <= N , Costi <= 106
1 <= X <= 1012
Sample Input(Plaintext Link)
1
5 12
1
3
4
5
2
Sample Output(Plaintext Link)
YES
MyApproach
I followed what is said to take the input and took the subarry sum for every element.But I am not getting Expected output.
public static void counCondition()
{
boolean b1=false;
int Sum=0;
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
sc.nextLine();
String nextLine = sc.nextLine(); //#Edited my mistake
String[] input = nextLine.split("\\s+");
int p = Integer.parseInt(input[0]);
int c = Integer.parseInt(input[1]);
int Cost[]=new int[p];
for(int j=0;j<Cost.length;j++)
{
Cost[j]=sc.nextInt();
}
for(int k=0;k<Cost.length;k++)
{
Sum=0;
for(int l=k;l<p;l++)
{
Sum=Sum+Cost[l];
if(Sum>c)
{
break;
}
else if(Sum==c)
{
b1=true;
break;
}
}
}
if(b1==true)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
sc.close();
}
//#Edit Output is still the same.
**ActualInput** **ExpectedInput**
1 1
5 12 5 12
1 1
3 3
4 4
5 5
2 2
6
7
8
9
2
**ActualOutput** Expected Output(Plaintext Link)
NO YES
I am not expecting this output.
Can anyone guide me why?
Once you have got the individual cost in the Cost array.
Here is the logic to get continous sum equal to max sum.
Maintain a start index variable telling from where continous sequence is starting. In the start it should be zero index.
Maintain sum variable to track the total sum.
Run a for loop from zero to endIndex.
if sum less than max sum
Add Cost[i] to sum.
else if sum equals max sum, break the for loop
else if sum greater than max sum
Now remove elements from startIndex till sum again becomes less or equal to max sum using while loop.
while(sum > maxSum)
sum = sum - cost[startIndex]
increment startIndex
while loop finished
if sum equals maxsum, break the loop you got your answer
else continue the outer for loop.
The idea of this logic is to keep removing elements from start from the sum whenever sum increases the maxsum.
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
int n=sc.nextInt();
long x=sc.nextLong();
long[] money=new long[n];
for(int i=0;i<n;i++)
{
money[i]=sc.nextInt();
}
long sum;
int c=0;
sum=money[0];
for(int i=1;i<n;i++)
{
if(sum<x)
sum=sum+money[i];
else if(sum==x)
break;
while(sum>x)
{
sum=sum-money[c];
c++;
}
}
if(sum==x)
System.out.println("YES");
else
System.out.println("NO");
t--;
}
here http://jayarampandava.blogspot.in/2015_10_01_archive.html
you can find the actual solution
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at app.HackerEarth25Dec2015.counCondition(HackerEarth25Dec2015.java:18)
The exception is occurring because you are calling next() method not the nextLine(). The next() method return the next token which 5 here not the complete line.
Also I would suggest you to use the nextInt() from the Scanner instead of getting the String and splitting and parsing it. That would be a cleaner way of doing things.
int p = sc.nextInt();
int c = sc.nextInt();
Also your logic is also not correct. I hope you will find the logical error and fix it.
You can use the below code for fixing the issue.
sc.nextLine(); // This is to read the `\n` left from previous `nextInt()`
String nextLine = sc.nextLine();
String[] input = nextLine.split("\\s+");

How do I update the integer while the loop is running?

When we enter 0 in the program it is supposed to stop running the loop and print the average of the numbers. When I run the program and initially enter 0, the program exits. If I enter in an integer that is not zero first, and then enter 0, the program keeps running and I can't quit.I figure that the integer value needs to update when the user enters a new value for the program to quit, and the sum to be correct.
How do I update the integer value while the loop is running? I should change or add something in the loop I'm guessing.
import java.util.Scanner;
public class Exercise05_01 {
public static void main(String[] args){
float negCount = 0;
float sum = 0;
float posCount = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a positive or negative integer. Entering 0 ends program");
int integer = input.nextInt();
while (integer != 0) {
if (integer > 0) {
posCount = +1;
sum = +integer;
}
if (integer < 0) {
negCount = +1;
sum = +integer;
}
float count = negCount + posCount;
if (integer == 0) {
System.out.println("The answer");
}
}
}
}
There are two problems.
First, you don't get any input while you're in the loop. That's fixable with a suggestion provided earlier by Lunchbox.
Second, this is not accumulating the value:
posCount = +1;
That assigns a positive 1 to posCount every time.
You want to either increment the value...
posCount++;
...or add one explicitly.
posCount += 1;
I think you need to add the line that gets input in your while loop.
while (integer != 0) {
integer = input.nextInt();
.
.
.
This way while the loop is running, every iteration it will check for an input still.
Also I have to say this looks suspiciously like homework... especially the class name...
As Lunchbox points out in his answer, you need to request input from the user from inside your loop, otherwise integer never changes and you never exit your loop; the behaviour you're observing is the program running forever.
The best way to do this is Lunchbox's suggestion:
int integer = input.nextInt();
while(integer != 0){
// Do stuff
integer = input.nextInt();
}
However, you have many other problems with your code. For one thing, why are you using floats to store your counters and sum values? Why not use ints?
For another, you're never actually incrementing those values. As Makoto points out in his answer, the line posCount = +1 is not an increment operator.
In that case, the + operator is the unary plus operator. What this will do is force your signed value to be positive, so +(-1) == 1. While this is useful, it's not what you want to happen, and it's definitely not what you want to be doing around your sum.
Instead, you want to do one of the following three things:
posCount = posCount + 1;
posCount += 1;
posCount++;
Those are all equivalent statements. The ++ operator is the postfix increment operator, which will add 1 to the value of the variable and then return it (It's slightly more complicated than that, but you can read that on your own time). So don't use that syntax for your sum; use one of the other two.

User input and finding multiples

I'm new to java and I have an assignment asking to prompt user for a number between 2 and 10 and it is supposed to print out multiples of that number. It is also supposed to use a for loop.
I think I have the general idea with the for loop I'm just trying to figure out how to do the multiples. Any help is greatly appreciated! This is where I am so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter a number between 2 and 10:");
for(int i = 2; i<= 100; i++){
System.out.println(+ i);
}
I suggest thinking about how you would go about doing the task mentally. When you're counting integers, you will add one each time (i++). When you're counting by, say threes, you will add three each time. You need to store your scanner's read value to a variable (don't try to read the scanner each time!) and adjust i++ in your loop to add the number you read from the scanner instead.
Begin with:
int step = in.nextInt();
if(step >= 2 && step <=10){
for(int i = 0; i <=100; ???){
System.out.println(+ i);
}
} else {
System.out.println("The step value was not between 2 and 10.");
}
I will leave you at this point as learning it for yourself is far more valuable than any Stack Overflow answer could ever be. If you are still stumped, I can guide you farther in the right direction.
You should ensure that the user can only enter numbers between 2 and 10, and you will need to store the input for use in your for loop. For example:
int num = 0;
Scanner in = new Scanner(System.in);
do
{
System.out.print("Please enter a number between 2 and 10:")
num = in.nextInt();
System.out.println();
} while((num < 2) || (num > 10));
Followed by your for loop.
A multiple of a number is that number times something.
So one multiple of i would be i * 13 (for example).
of course you need to get number from the Scanner "in" object
for (int i=2; i < 13; i++) {
System.out.println(" Multiple (" + i + ") = " + i*number;
}

Categories

Resources