Printing Fibonacci series between 1-99 - java

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();

Related

Java while loop help to compute the frequency of even numbers from the user

My Question that I am trying to solve is as follows: "Read in numbers from the user until the user enters -1, and compute the frequency of even numbers from the user".
I have the first part done and it seems to run ok. But I cant get the second part completed where I compute the frequency of even number from the user.
I have copied what I have done so far but i am looking for help to finish it of. I would appreciate anyone's help.
import javax.swing.JOptionPane;
public class Ex2Ass2ParC {
public static void main(String[] args){
String dataString = JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
int data = Integer.parseInt(dataString);
int count = 0;
while(data!=-1){
count++;
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
}
JOptionPane.showMessageDialog(null, "The frequency of numbers is"+count);
}
}
}
Add an if statement to check if a number is even instead of just adding to count every time by doing:
if (data % 2 == 0) {
count++;
}
So replace count++ with the statement above.
EDIT
If by frequency you mean percentage, you'll need to create a second local variable that keeps track of the total amount of numbers given
double totalNumbers = 0.0;
while(data!=-1){
totalNumbers++;
if (data % 2 == 0) {
count++;
}
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
}
And then change the dialog to JOptionPane.showMessageDialog(null, "The frequency is: " + (count/totalNumbers));
In order to compute frequency of numbers of a certain kind you need to count how many such numbers were entered, in addition to the total count of numbers, which you already have.
Add a separate counter, and increment it each time that data % 2 == 0, which indicates that the parsed number is even:
int count = 0;
int even = 0;
while(data!=-1){
count++;
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
if (data % 2 == 0) {
even++;
}
}
At the end of the loop divide the count of even numbers by the total count. Make sure that you cast the first count to double before performing division, otherwise you would get an integer division resulting in zero or one.

How to read all the elements of array at once and determine what already exists in the array?

Use a one-dimensional array to solve the following problem:
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
My program is running fine for the most part. The only problem I'm facing is when i input the second element of the array to check when the first one is asked to input, it outputs "the number is not in the array". Even though the number is in the array. Please go easy on me because i am pretty naive with programming.
import java.util.Scanner;
public class DuplicateElimination {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// the variable to read the number
int number = 0;
// the array with the elements needed to be checked
int [] array = {12, 33, 54, 90, 100, 1};
// for loop to ask the question if the number is in the array.
for(int counter = 0; counter < array.length; counter++ )
{
System.out.print("Enter a number to check: ");
number = input.nextInt();
if (number == array[counter])
System.out.printf("The number %d is already in the array.\n\n", array[counter]);
else
System.out.printf("The number %d is not in the array.\n\n", number);
}
}
}
P.S this is not a homework I'm just doing it to keep me in practice.
Using this condition:
if (number == array[counter])
You're evaluating if the current value of number is equals to a single value inside the array. In order to evaluate if the value of number is stored in array is to check all the values inside array. Here's an example of how to achieve it:
boolean found = false;
for (int j = 0; j < currentSizeOfArray; j++) {
if (number == array[j]) {
found = true;
break;
}
}
if (found) {
//do something
}
Another hint to solve your homework: use a while loop to read the data, not a for loop. Also, have a temporal variable that maintains the current number of elements in the array, which is not the same as the length of the array.

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.

Help with understanding java 'for' loops

I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!
Example #1 (odd number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>
Example #2 (even number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>
a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:
for(counter=0;counter <= iterations;counter++){ }
the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.
if we want to loop from 1 - 10, we do the following:
for(counter=1;counter<=10;counter++){ System.out.println(counter); }
if we want to loop from 10 - 1, we do the following:
for(counter=10;counter>=1;counter--){ System.out.println(counter); }
if we want to loop through a 2 dimensional collection, like...
1 2 3
4 5 6
7 8 9
int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.
you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.
for(i=0;i<grid.length;i++){
//this will loop through all rows...
for(j=0;j<grid[i].length;j++){
//will go through all the columns in the first row, then all the cols in the 2nd row,etc
System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
}
}
In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.
We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.
Please feel free to ask any questions you may have regarding for loops!
EDIT: understanding the question.....
You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.
int lines = 10; //the number of lines
String carat = ">";
for(i=1;i<=lines;i++){
System.out.println(carat + "\n"); // last part for a newline
carat = carat + ">>";
}
The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.
.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.
Edit 3:
Class Test {
public static void main(String[] args) {
int lines = 7;
int half = lines/2;
boolean even = false;
String carat = ">";
int i;
if(lines%2==0){even = true;} //if it is an even number, remainder will be 0
for(i=1;i<=lines;i++){
System.out.println(carat + "\n");
if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
carat = carat.substring(0,carat.length()-2);
}else{
carat = carat + ">>"; //otherwise, going up
}
}
}
}
Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).
Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.
At the hump, if it is even, we have to repeat the string.
We have to then start taking off "<<" each time, since we are going down.
Please ask if you have questions.
I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.
There is a lot of commenting throughout the code that you can follow along to explain the logic.
class ArrowTip {
public void printFigure(int n) { //The user will be asked to pass an integer that will determine the length of the ArrowTip
int half = n/2; //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
String str = ">"; //The String to be printed that will ultimately create the ArrowTip
int endInd; //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip
for(int i = 1; i <= n; i++) { //Print this length (rows)
System.out.print(str + "\n"); //The first carat to be printed, then any following carats.
if (n%2==0) { //If n is even, then these loops will continue to loop as long as i is less than n.
if(i <= half) { //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
str = str + ">>"; //It will continue to add two carats to the string until i is greater than n.
}
endInd = str.length()-2; //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
if((endInd >= 0) && (i >= half)){ //Now, decrement the str while j is greater than half
str = str.substring(0, endInd); //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
}
}
else { //If integer n is odd, this else statement will be called.
if(i < half+1) { //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
}
endInd = str.length()-2; //Serves the same purpose as the above if-loop when n is even.
if((endInd >= 0) && (i > half)) { //This will create the bottom half of the ArrowTip by decrementing the carats.
str = str.substring(0, endInd); //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
}
}
}
}
}
Again, this was for a homework assignment. Happy coding.
Here is a simple answer for you hope it helps! Cheers Logan.
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
for (int i = 10; i > 0; i--) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
}
}
For making a 'for' loop:
public class Int {
public static void main(String[] args) {
for (Long num = 1000000L; num >= 9; num++) {
System.out.print("Number: " + num + " ");
}
}
}
Output:
Number: 1008304 Number: 1008305 Number: 1008306 Number: 1008307 ...

How to exit the loop with the number 0? but now i have other problems

package hw3;
public class Main {
public static void main(String[] args) {
final int NumberOfElements = 1000;
int[] num = new int[NumberOfElements];
int var = 0;
//create input
java.util.Scanner input = new java.util.Scanner(System.in);
for (int i = 0; i < NumberOfElements; i++) {
System.out.print("Enter any positive number or enter 0 to stop: ");
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
}
Arrays.sort( num, 0, var);
int i;
for (i = 0; i < var; i++) {
System.out.print(" " + num[i]);
}
}
}
Write a Java program reading a sequence of positive integers entered one per line. The program stops reading when integer ‘0’ is entered. The program will sort and output them into an ascending numerical order.For example: 5
1
7
12
36
8
0
Output: 1 5 7 8 12 36
Try to understand the problem: there are three steps.
Step 1: Get the input from the user. Continue getting input till the user enters 0
Step 2: Sort
Step 3: Print out the results
Step 1: Your for loop is almost correct.
But the for loop should end immediately after you have got the input.
In the following code,
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
you are adding the user input to the array and then checking whether it is 0. This means that the 0 will also be part of your array. If you don't want this, you should check the input and add it to the array only if it is not 0.
Also note the declaration of i before the for loop. Because we need it after the for loop. Why? see below.
int i = 0;
for (i = 0; i < NumberOfElements; i++) {
int n = input.nextInt();
if (n == 0)
break;
else
num[i] = n;
} //for loop ends here
Step 2: Sort it
Arrays.sort(num);
Step 3: Print the output:
for (i = 0; i < num.length; i++) {
System.out.print(" " + num[i]);
}
The problem is, in step 2, an array of 1000 elements is sorted, while you actually need to consider only the number of elements the user has entered. You don't know that initially thats why you created an array of 1000 elements.But, at this point (after step 2) you do know how many number of elements the user has entered. This is present in i
So new step between 1 and 2: Create a new arrays that contains only those elements that the user has entered.
Step 1.5:
int[] newArray = Arrays.copyOf(num, i);
Now sort this new array, and print it (same as your code, but uses the new array we just created)
Arrays.sort(newArray);
for (i = 0; i < newArray.length; i++) {
System.out.print(" " + newArray[i]);
}
Notes:
1. The ideal way to do this is to use Lists and not arrays, but probably since this is homework, you might have to use arrays.
Since this is homework, I don't know whether you are allowed to use Arrays.sort or Arrays.copy. Your professor might frown at this because perhaps his intention was that you learn the constructs of the language via for, if and while. In that case you have to do step 1.5 (make array the right size) and sort by yourself.
This is not difficult (but just remember this is not the best way to do it, except for in a homework)
Copy array (homemade) (in place of step 1.4 above)
int[] newArray = new int[i]
for(int j=0; j<i; j++){
newArray[j] = num[j];
}
Sort (homemade) (in place of step 2 above):
Loop through the elements
If one element is greater than the previous element, swap them (in asc order, the prev element is always lesser or equal to the next element)
There are two loops because you have to do the comparison on a continuous basis: the the first element, compare with the entire array, place it in the right position, take the second compare with the entire array etc...)
for(int j=0; j<newArray.length; j++) {
for(int k=0; k<newArray.length; k++) {
if(newArray[k] > newArray[j]) {
//the swap logic:
int t = newArray[k];
newArray[k] = newArray[j];
newArray[j] = t;
}
}
}
Try to understand what really is happening, instead of just copy pasting.
Once you understand the homemade sort logic, think about this:
The second for loop in the sort or(int k=0; k<newArray.length; k++) { can actually just be for(int k=0; k<newArray.length; k++) {. Why?
Your print loop will remain the way you wrote it, but you will print newArray rather than num. You might want to change the loop variable to int j or something, but i will also work. (i holds the no of inputs now, so I would not use it for any other purpose. But it is just a manner of coding. Technically no difference - the code will work the same way)
I am not combining the parts. I leave that o you, otherwise it will look like I did your homework :-)
num[i] holds the last number you are reading. So you have to compare it against 0 and if it is 0, you have to end the loop. Read about branching statements to find out how to do that.
It is probably also good for you to read about control flow statements in general.
Here your application is reading int, you can check that the last one is != from 0. And break the loop.
If you don't like using break, you can still add a condition to your for.
For sorting an array, there is the Arrays.sort() solution.
And to print them you'll need another loop, but beware as you can have less than 1000 items in your array you can't simply print the whole array.
You'll need to find a way to count the number of elements you added in the array.
After your edit:
Good your application seems to work here is what I got :
Mac-Makkhdyn:~ Makkhdyn$ java hw3.Main
Enter any positive number or enter 0 to stop: 1
Enter any positive number or enter 0 to stop: 2
Enter any positive number or enter 0 to stop: 3
Enter any positive number or enter 0 to stop: 4
Enter any positive number or enter 0 to stop: 5
Enter any positive number or enter 0 to stop: 0
Mac-Makkhdyn:~ Makkhdyn$
The 0 you have must be from somewhere else. Isn't your actual code slightly different from the one you posted here ?
Resources :
javadoc - Arrays.sort()
Java tutorial - The break Statement

Categories

Resources