Are for loops and while loops always interchangeable - java

I understand the concept of one having certain advantages over the other depending on the situation but are they interchangeable in every circumstance? My textbooks writes
for (init; test; step) {
statements;
}
is identical to
init;
while (test) {
statements;
step;
}
How would I rewrite the following program in the for loop? I'm having trouble setting the value for the init and the test if i rework the following program into the for loop form.
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
int n = readInt("enter a positive number: ");
int dsum = 0;
while ( n > 0) {
dsum += n % 10;
n /=10;
}
}
}

int dsum = 0;
for(int n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}

As I can't stop myself from writing this, so I'll point it out.
Your for loop: -
for (init; test; step) {
statements;
}
Is not identical to the while loop you posted. The init of the for loop will not be visible outside the loop, whereas, in your while loop, it would be. So, it's just about scope of the variable declared in init part of for loop. It is just inside the loop.
So, here's the exact conversion of your for loop: -
{
init;
while (test) {
statements;
step;
}
}
As far as the conversion of your specific case is concerned, I think you already got the answer.
Well, by the above explanation, the exact conversion of your while loop is a little different from the #Eric's version above, and would be like this: -
int dsum = 0;
int n = 0;
for(n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
Note that this has a very little modification from the the #Eric's answer, in that, it has the declaration of loop variable n outside the for loop. This just follows from the explanation I gave.

Beside the scope of variables declared in the initializer, there is another time when a for will exhibit different behavior, which is in the presence of a continue:
for (init; test; update) {
if(sometest) { continue; }
statements;
}
is NOT identical to
init;
while (test) {
if(sometest) { continue; }
statements;
update;
}
because in the while loop the continue it will skip update, where the for loop will not.
To show this via the starkest of examples, consider the following two loops (thanks #Cruncher):
// terminates
for(int xa=0; xa<10; xa++) { continue; }
// loops forever
int xa=0;
while(xa<10) { continue; xa++; }

+1, good question
The difference between the two is mostly eye-candy. In the one instance the one may simply read better than the other. For your example, the following is the for-loop equivalent in a single line of code. In this case, however, the while loop reads easier.
public void run() {
println("this program sums the digits in an integer");
for (n = readInt("enter a positive number: "), dsum=0; n > 0; dsum+=n%10, n/=10);
}

Yes, except for the two things:
"For" let you declare and initialize your conditions (= variables, btw - more than one variable!) in it, and then it is cleaned up automatically, as you leave the "For" cycle.
Whereas with "While" you will have to do it yourself, initialize - outside the "While", clean up - only as you leave the of visibility where your variables (for conditions) were declared.
"For" has convenient syntax (and all cleanup afterwards) for iteration over collections and arrays.
Your code I would rewrite this way:
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
for(int n = readInt("enter a positive number: "), dsum = 0; n > 0; n /=10) {
dsum += n % 10;
}
}
}
Don't forget - in init you can place declaration/initialization for more than one variable.

what kind of difficulties you have,anyway
int n = readInt("enter a positive number: ");
for(n;n>0;n=n/10)
{dsum+=n%10;
}

This should work. Replace your while loop with this. Just leave the initialization part empty.
for(;n>0;n=n/10)
{
dsum+=n%10;
}

Related

Method to print odd numbers between 1 and 100

I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working.
Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number + 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i++) {
isOdd(i);
}
System.out.println(i);
}
Your attempt #1 is closer to your goal ;)
you are right that you can use while and for (and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now)
your println (or print) should be within the loop because you want to print more than just one number.
in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if inside your loop where you check the result of isOdd(number) and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number + 2;), your program will only need half the time - and you could even skip the isOdd check ;-)
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for-loops are just syntactic sugar for special while-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for-loop.
for-loop
for (int i = 1; i < 100; i++)
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i as int in the for-loop initializer.
Now, we may translate this to an equivalent while-loop:
while-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i++;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if inside the loop body); the first even number (2) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd here. You're unconditionally printing i after the loop has terminated, which will always be 100.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i += 2)
System.out.println(i);

How to write a method that returns how many number 2 are present in an integer without a do loop

This is what i have:
int count = 0;
do {
if(number % 10 == 2){
count++;
}
number = number /10;
} while (number > 0);
return count;
It works fine but is there a way to write it without using the do loop? I have an assignment that doesn't allow it
I'm new at java so let me know if you need me to clarify something let me know
There are hundreds of ways to approach this. The while code looks pretty similar to your do-while:
int count = 0;
while(number > 0) {
if (number % 10 == 2) count++;
number /= 10;
}
return count;
String replace is a cute tactic (though perhaps not efficient):
// total length - length without 2s = length of 2s
String numStr = String.valueOf(num);
int count = numStr.length() - numStr.replace("2", "").length()
Elliot's version is even sexier:
// Replace all "not 2s" and count length
int count = String.valueOf(num).replaceAll("[^2]", "").length();
What you are using is a 'do-while' loop which is an exit control loop and I'm glad you are trying to learn how to convert between loops.
The most useful and efficient loop for this code is going to be the 'while' loop since the 'for' loop is usually used for iterations in which we know the end goal or number of interations on the whole.
public int method(int number){
int count = 0;
while(number > 0) {
if (number % 10 == 2) {
count++;
}
number = number / 10;
}
return count;
}
The above example is for your code to be converted to the 'while' loop. The basic code is the same however the java statement in the 'do' bloc become the part of the 'while' bloc.
It is not recommended to use the 'for' loop here since it is going to complicate the process unneccsarily however for the sake of curiosity this is the code.
public int method(int number){
int count;
for(count = 0; number > 0 ; count++){
if((number % 10) != 2){
count--;
}
number = number / 10;
}
return count;
}
The above code is one way of executing the 'for' loop. Note that in the 'for' loop the count increases without any condition hence, in the loop we have added a count-- to prevent the unintended increment in the count variable.
I have used something called 'shorthand operators' which can make statements like number = number / 10 smaller like this, number /= 10.
Do let me know if you find anything complicated and keep experimenting. It's rare to find the questions like these which are conceptual and technically basic but I am glad this community is vast.
Let me know about any further queries, I had a lot of fun answering this!
It would be something like this:
while(number > 0) {
if(number % 10 == 2) {
count++;
}
number /= 10;
}
The only difference is that a while loop will only run if its condition is met, while a do-while loop will run at least once.
try this:
public class Sample{
static int count = 0;
public static void main(String []args){
System.out.println(Sample.Count(50));
}
public static int Count(int number){
if(number>0){
if(number%10==2){
count++;
}
number = number/10;
Count(number);
}
return count;
}
}

program is taking input infinitely despite the program scanning one element at a time

I am trying to take input into the variable n. However, it gets infinitelly stuck when trying to take input.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
int i,r=0,max=0;
Scanner s=new Scanner(System.in);
//int i,r=0,max=0;
int n=s.nextInt();
for(i=1;i<=n;i++)
{
while(i>0)
{
r+=i%10;
i/=10;
}
if(max<=r)
max=r;
r=0;
}
System.out.print(max);
}
}
I want the program to take one input, then proceed further in the program and compute the result. But, instead it gets stuck while trying to recieve input.
The problem is that the inner while loop will terminate when i becomes zero. But, the outer for loop will happily keep iterating. So the infinite loop is actually the for loop, which will never end. Without knowing exactly what your code is supposed to be doing, I can suggest that you use another variable instead of i directly:
for (i=1; i <= n; i++) {
int j = i;
while (j > 0) { // use variable j to do the math; don't change loop counter i
r += j % 10;
j /= 10;
}
if (max <= r) { // possibly record a new max value
max = r;
}
r = 0; // always reset r
}
You should use while(i>1) instead. Using while(i>0) doesn't work because you're trying to reach 0 through division, so the loop becomes infinite.

two loops in a function?

Is it possible to have two loops in a function?
public static void reduce(Rational fraction){
int divisorNum = 0;
int n = 2;
while(n < fraction.num){
if(fraction.num % n == 0){
divisorNum = n;
System.out.println("n: " + divisorNum);
n++;
}
}
int divisorDenom = 1;
int m = 2;
while(m<fraction.denom){
if(fraction.denom % m == 0){
divisorDenom = m;
System.out.println("m: " + divisorDenom);
m++;
}
}
}
I'm trying to get the greatest common denominator. I know this is the very long way about doing this problem but I just wanted to try having two loops. When I call this function, only the first loop gets printed and not the second. I originally had an if statement, but seeing that the second loop doesn't execute I figured that I fix this part first.
Here's my other part of the code:
public static void main(String[] args){
Rational fraction = new Rational();
fraction.num = 36;
fraction.denom = 20;
reduce(fraction);
}
Absolutely. There are no limitations
Watch your conditional test = is not quite ==
Based on your edit I suspect fraction.denom is initialized at 1 or 0
Hence you will never get in the second loop
You can have any number of loops in your function :-
1.You can have nested loops;
2.Two loops side by side.
SO,your piece of code is fine enough considering the value of n, until the conditions for loop execution are met :-
public static void ....
while(n<x){
do this
add to counter
}
while(m<x){
do this
add to counter
}
if(y==z){ // NOTE :- Here you have committed mistake, compare using ==, not by =(it will be always true else and your condition will always be met else)
print this
}
Yup. You even can have 3 if you try hard enough.
EDIT: The didactic version:
Loops, as the name suggest, are constructs that allow you to repeat blocks of code several times (post conditional loops -> until certain condition is met keep running, pre conditional loops -> if certain condition is met, keep running). This is often called "iteration". So in a typical for-loop:
for ( int i = 0; i < 10; ++i )
print(array[i]);
You can say you're "iterating" over the array 10 times.
This has nothing to do with functions. You can have several loops inside a function, or functions being called inside loops. As long as you define your "blocks" of code (with begining and ending braces) you do what you think its best.
Yes, there are no limitations when it comes to looping. You could do 1000 while loops if you wanted.
An example here could be doing something like making a square out of *...
Here's an example
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("*");
}
System.out.println();
}
It would look like:
****
****
****
****

Why doesn't my program that computes perfect numbers print anything?

I got an assignment to create a program which displays the perfect integers between one and 100. Here is the actual assignment:
Create a PerfectIntegers application that displays all perfect integers up to 100. A perfect integer is a number which is equal to the sum of all its factors except itself. For example, 6 is a perfect number because 1 + 2 + 3 = 6. The application should include a boolean method isPerfect().
I tried and came up with this:
import java.util.ArrayList;
public class PerfectIntegers {
public static boolean isPerfect(int a){
ArrayList<Integer> factors = new ArrayList<Integer>();
int sum=0;
boolean is;
for (int i=1; i<=100; i++){
double r=a/i;
if (r%1==0){
factors.add(i);
}
}for (int i=0;i<factors.size();i++){
sum+=factors.get(i);
}if (sum==a){
is=true;
}else{
is=false;
}return is;
}
public static void getInts(){
for (int i=2; i<=100; i++){
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
getInts();
}
}
Eclipse did not show any errors but when I try to run it, the program is terminated and I get nothing.
The problem is likely with double r, as it is not dividing properly 100% of the time.
Your factorization code is wrong. You can fix it like this:
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
factors.add(i);
}
}
One reason your old code did not work is that you misunderstood the workings of the % operator. It computes the remainder of the division of the left-hand side by the right-hand side, so r % 1 == 0 will be true for all numbers, because 1 divides everything; r % 2 == 0 is a way to detect even numbers, and so on.
The other reason is that you went all the way to 100 in search of divisors. This necessarily includes a, which automatically puts the total above the number itself, because 1 is already on the list.
Once you get this working, you could simplify the code by dropping the list of factors. Since the sum of all factors is all that you need, you might as well compute it in the factorization loop, and drop the loop that follows it:
sum = 0;
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
sum += i;
}
}
dasblinkenlight has already provided the correct answer. Let me just add that since this seems to be a (potentially graded) assignment you might consider refactoring the getInts() method as well.
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
is actually equal to
if (isPerfect(i)){
System.out.print(i+" ");
}
since isPerfect() already returns a boolean that can be used inside the condition of the if-statement.
It can be argued (even though I strongly disagree in this concrete case) that it might be more readable to first store the return value in a variable like in in the first variation. But even then you should never have to check for
if (is!=false) { //...
but should be using
if (is) { // ...
instead.

Categories

Resources