a while loop for printing multiple of 3 - java

Your program should print the following:
0 3 6 9 12 15 18 loop ended!
This is my code. May I know why can't I do the desired output?
int i = 0;
while(i%3 == 0 && i < 20 ) {
System.out.print(i);
i++;
}
System.out.print("loop ended!");

You have a condition in your while loop that must be satisfied for the while loop to continue running. When i increments to 1, the while loop condition fails and thus will stop running, so your program will only print 0. You instead should use an if statement inside the while loop with the mod condition:
int i = 0;
while(i < 20) {
if(i%3 == 0) {
System.out.print(i + " ");
}
i++;
}
System.out.print("loop ended!");

i % 3 == 0 && i < 20 - this condition evaluates to false when the value of i becomes 1. So loop only executes once.
You just need i < 20 as a loop condition and in each iteration of the loop, just add 3 in i.
int i = 0;
while(i < 20) {
System.out.print(i + " ");
i += 3;
}
System.out.print("loop ended!");
Output:
0 3 6 9 12 15 18 loop ended!

public static void main(String... args) {
int i = 0;
do {
System.out.print(i + " ");
} while ((i += 3) < 20);
System.out.print("loop ended!");
}
I offer to simplify your code with usein for loop:
public static void main(String... args) {
for (int i = 0; i < 20; i += 3)
System.out.print(i + " ");
System.out.print("loop ended!");
}

Related

I am getting unexpected output from this code:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int i = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
while(i<y){
for ( i = 1; i <=y; i=i+x) {
for ( int j = i; j <=(i+(x-1)); j++) {
if(x%2==0 && y%3==0)
{
System.out.print((j-1)+" ");
}
else
System.out.print(j+" ");
}
System.out.println();
}
}
Sample input:
3 99
This is the output I am supposed to get :
1 2 3
4 5 6
7 8 9
10 11 12
...
97 98 99
But when I give my input as
4 99
The output I get is :
0 1 2 3
4 5 6 7
....
96 97 98 99
I am not supposed to start with 0.
What is wrong in my code?
I tried to rewrite your code a little so that it isn't so messy. Is this what you want to achieve?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=input.nextInt();
int y=input.nextInt();
for (int i = 1; i < y + 1; i++) {
System.out.print(i + " ");
if (i % x == 0){
System.out.println();
}
}
input.close();
}
Scanner input=new Scanner(System.in);
int i = 1;
int j = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
for( i = 1; i <=y; i++) {
System.out.print(i);
System.out.print(" ");
j++;
if(j == x){
System.out.println();
j = 0;
}
}
you can use this code to output as you expect.
Your first output is going to be a 4 because at that time x = 3 and y = 99. Neither are even so your else block will be hit. Change if(x%2==0 && y%3==0) to if(x%2==0 || y%3==0) and you will get 0 for the first output. That won't totally fix your problem but it will get you on the right path.
You begin j=1 (because i = 1 the first time you enter the loop)
and if x%2 == 0 (which is the case) you print j-1
of course you will begin with 0, I don't see why you're surprised.
if you want to avoid that, just print :
(j-1)==0 ? "" : j-1 + " "

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Add two array elements using loop

I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {
public static void main(String []args)
{
int[] nums = new int[2];
for (int i = 0; i < 100; i++)
{
nums[i] = i + 1;
System.out.println(i);
}
System.out.println(nums[1]);
System.out.println(nums[2]);
if (nums[0]+nums[1]<=50)
{
System.out.printf("Sucessfully finished");
}
}
}
Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .
There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] <= 50) {
System.out.println("sum is less than or equal to 50");
break;
}
}
What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] > 50) {
System.out.println("sum was NOT less than or equal to 50");
break;
}
}
As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;
// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);
System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);
The output is min increments with sum > 50 was 25 and 26.
I believe, you need 1 more for loop, to go about checking each num[i] + num[i+1]. You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{
public static void main(String[] args) {
int[] nums = new int[100];
for (int i = 0; i < 100; i++) {
nums[i] = i + 1;
System.out.println(i);
}
for (int i = 0; i < 99; i++) {
System.out.println(nums[i]);
System.out.println(nums[i+1]);
if (nums[i] + nums[i+1] == 50) {
System.out.printf("Successfully finished");
}
}
}
}
I'm not sure if this is what you meant. Have a try.
public static void main(String[] args) {
int[] nums = new int[100];
nums[0] =1;
for (int i = 1; i < 100; i++) {
nums[i] = i + 1;
if ((nums[i] +nums[i-1]) >= 50) {
System.out.printf("Successfully finished");
}
}
}
I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
int j = i+1;
int total = i+j;
if((i+(i+1)) < 50) {
System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
}
}
This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)

Output is not getting displayed

I am writing a simple java program to find the smallest number which is divisible by all the numbers from 1 to 20.
I have written the following code:
package smallmultiple;
public class SmallMultiple {
public static void main(String[] args) {
int sml = 0;
outerloop:
for (int i = 40; i < 100000; i++) {
int j=1;
do {
if(i%j==0)
j++;
} while(j<21);
if(j==20) {
sml=i;
break outerloop;
}
}
System.out.println(sml);
}
}
It is not giving any error but it is not giving any output.
You can try this which is a bit faster than yours solution:-
for(int i = 190; ; i += 190) {
if(i % 3 == 0
&& i % 4 == 0
&& i % 6 == 0
&& i % 7 == 0
&& i % 8 == 0
&& i % 9 == 0
&& i % 11 == 0
&& i % 12 == 0
&& i % 13 == 0
&& i % 14 == 0
&& i % 15 == 0
&& i % 16 == 0
&& i % 17 == 0
&& i % 18 == 0
&& i % 20 == 0) {
System.out.println(i);
break;
}
}
You can also check out this article.
You are incrementing j only if i is perfectly divisible by j. Shouldn't you break or exit the do.. while loop of atleast one number is not divisible? Not doing so is causing infinite loop I believe. It should be something like
if(i%j==0) {
j++;
}
else {
break;
}
its simple. Let me explain your loop. First, i = 40 and j = 1, its ok. Then j++.Next i = 40 and j = 2, its still correctly. Then j++ again. Now i = 40, j = 3 and i%j !=0 => j cannot ++ and j still equal 3. And you see, j = 3 is still satisfy your loop ( j < 21) then it loop and loop forever. This is the reason why you cant get any output. You can use your IDE debugging to find this mistake. Sorry my English not good.
In java, to respect the object oriented best practise, it's not advised to user labels, try this :
public class NumberTool {
public static void main(String[] args) {
System.out.println("Smallest number is : " + getSmallestNumberDividedByOneToTwnety());
}
public static int getSmallestNumberDividedByOneToTwnety() {
for ( int i = 40; i <= 2147483647; i++) {
if (isNumberDivdedByOneToTwenty(i)) {
return i;
}
}
return 0;
}
public static boolean isNumberDivdedByOneToTwenty(int numberToTest) {
for (int i = 1; i <= 20; i++) {
if (numberToTest % i != 0) {
return false;
}
}
return true;
}
}
Output is:
Smallest number is : 232792560

writing a function that takes int n and returns the sum of odd less than n

Here is my code
public static int sumOfOddLessThan(int n)
{
int iResult = 0;
for(int i = n - 1; i > 0 && i % 2 != 0; i--)
{
iResult = iResult + i;
}
return iResult;
}
It does not work correctly, I dunno why :\
It should return 4 when I enter 5 but it returns 0
Your conditional in the for loop reads:
i is greater than 0 and i is not even.
When you call the method with 5 as argument, the first value of i will be 4, which is even and therefore the loop does not get evaluated.
for(i = n-1; i > 0; i++) {
if(i%2==0) {
iResult += i;
}
}
You're putting the condition i % 2 != 0 in the for loop instead of an if inside of the loop, hence if it's not met even once it breaks out of the entire loop.
Your code should look like this:
public static int sumOfOddLessThan(int n)
{
int iResult = 0;
for(int i = n - 1; i > 0; i--)
{
if(i % 2 != 0) {
iResult = iResult + i;
}
}
return iResult;
}
Then again you don't even need a loop, you can evaluate it directly by getting the number of odd numbers lower than N and squaring that.
you should modify the forumla used for adding the series, all you gotta do is to modify it
earlier
int i = (n+1)/2;
return (i*i)
modified
int i = n/2;
return (i*i);
TEST
input 1:
return 0;
input 2:
return 1;
input 3:
return 1;
input 4:
return 4;
input 5:
return 4;
input 6:
return 9;
and so on ..
The second part of a for loop is a continuation condition. In your case, your continuation condition is i > 0 && i % 2 != 0.
For n = 5, the first i is 4, and 4 % 2 is 0. Your continuation condition is not met, and this is why your for loop exits before it begins.
Try
for(int i = n - 1; i > 0; i--)
{
if (i % 2 != 0)
{
iResult = iResult + i;
}
}
The problem is that when the condition in the for is false, the loop exits.
So for 5, i=4 and i % 2 != 0 is false, so the loop isn't accessed at all.
Try this instead:
for(i=((n-1)%2==0?n-2:n-1 ; i>0; i=i-2)
{
i > 0 && i % 2 != 0;
}
Note that by reducing 2 from i at each step, you don't have to check parity on every loop.
First you are setting i as n-1, so it would be 4 if n is 5, then your condition on the for loop states that i must be odd, which 4 is not, so it doesn't even do one loop. Try this:
public static int sumOfOddLessThan(int n)
{
int iResult = 0;
for(int i = n-1; i > 0; i--)
{
if (i % 2 != 0) iResult += i;
}
return iResult;
}

Categories