I'm trying to print following pattern:
0
11
0
222
0
3333
0
222
0
11
0
I want to achieve this by using recursion and a loop inside said recursive method, which gets one integer value passed. The int value determines how far this pyramid pattern goes. In the example above the int value would be 3.
I managed to get the bottom half, but I have no idea to get the upper half.
if (arg != 0) {
System.out.println("0");
for (int i = 0; i <= arg; i++) {
System.out.print(arg);
}
System.out.println();
print(arg - 1);
}
How would I be able to somehow implement some increment, which turns to a decrement to this recursion? Since I'm thinking this would be how I could achieve the above pattern.
Thank you very much in advance!
You can pass two arguments. The Max value and start value which will be zero and
then increment start value until reaches max
then decrement Max until reaches zero
call--> printline(3);
private static void printline(int input, int... vars) {
if (input == 0) {
System.out.println(0);
return;
}
int start= vars.length > 0 ? vars[0] : 0;
start++;
System.out.println("0");
for (int i = 0; (i <= start && i <= input); i++) {
System.out.print(start >= input ? input : start);
}
System.out.println();
if (start >= input) {
input--;
}
printline(input, start);
}
}
Related
I'm a total begginer in java and I'm having some trouble at understanding how things work... could someone explain to me why the computer understands "i" as horizontal row and "j" as vertical row since both "for" loops are the same, just with different variables?
public class DiagonalStar {
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
} else {
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
if ((i == 1) || (j == 1) || (i == number) || (j == number) || (i == j) || (j == number - i + 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
It's actually not a matter of vertical or horizontal, is based on the order the lines of code are executed.
For example:
for(int n=0;n<10;n++)
{
System.out.println(n);
}
Would print
0
1
2
3
4
5
6
7
8
9
But if you put another loop inside it, it will execute it before passing to the next loop of n.
for(int n=0;n<10;n++)
{
for(int m=10;m<15;m++)
{
System.out.println(n + "." + m);
}
}
That would print
0.10
0.11
0.12
0.13
0.14
0.15
All that before getting to 1.10, 1.11, etc...
So when you're printing the "*" you're just looping in that logic, and whenever you complete the inner for you use println (that prints the next line)
I would suggest messing with the variables, see what the program outputs when you switch i with j or when you change the conditions.
Good luck!
You have nested one for loop into another. This means that for each value of i you are going thru all values of j.
After inner loop you have System.out.println() and this moves you to another row.
println() - prints text with a newline
print() - just prints text
System.out.print prints in a row, while System.out.println prints in a column
How to exit from a method, i.e how can i return from a function in this recursion in java?
public class solution {
public static int countZerosRec(int input){
int n=0;
int k =0;
int count=0;
//Base case
if(n==0)
{
return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
}
k=input%10;
count++;
n=input/10;
countZerosRec(n);
int myans=count;
return myans;
}
}
Please help me getting out of this method.
This is a program to count number of zeroes.
Example, 34029030 ans = 3
You can try below approach:
public class MyClass {
public static void main(String args[]) {
System.out.println("total zeroes = " + returnZeroesCount(40300));
}
public static int returnZeroesCount(int input){
if(input == 0)
return 0;
int n = input % 10;
return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
}
}
How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.
For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.
In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.
For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.
If your main focus is to find number of zeroes in a given number , You can use this alternatively:
int numOfZeroes =0;
long example = 670880930;
String zeroCounter = String.valueOf(example);
for(int i=0; i< example.length();i++){
if(zeroCounter.charAt(i) ==0){
numOfZeroes++;
}
}
System.out.print("Num of Zeros are"+ numOfZeroes);` `
Instead of posting a code answer to your question, I'll post a few pointers to get you moving.
As #jrahhali said, as your code is, it'll not get past the return
statement inside the if block(which is an error BTW, because you have an int return
type).
I'd recommend that you move the last two lines to some calling
function(such as a main method). That way all this function will
need to do is do some basic processing and move forward.
You aren't checking k at all. As it is, your count is going to
always increment.
Hope this much is enough for you to figure things out.
int count =0;
private int getZeroCount(int num){
if(num+"".length == 1){
if(num==0){
count++;
}
return count;
}
if(num%10 == 0){
count++;
}
num /= 10;
getZeroCount();
}
Method1 :
public static int countZero1(int input) {
int count = 0;
//The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
// When the value of the input is less than 0, the cycle ends
while (input >0){
if (input % 10 == 0){
count ++;
}
input /= 10;
}
return count;
}
Method2 :
private static int count = 0;
public static int countZero2(int input) {
//Recursive call function
if (input % 10 == 0){
count ++;
}
input /= 10;
if (input <= 0){
return count;
}else {
return countZero2(input);
}
}
class Labo21
{
public static void main(String [] arguments){
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = Clavier.lireInt(); //keyboard
if( n <= 0){
System.out.print("ERROR");
}else{
i = 2;
somme = 1;
while (n <= i){
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
I try to know why I cannot enter the while loop.
This code has a problem with its mentality. You are lucky that it is not going into the loop though. If it so, it would run without stopping and you cannot understand it.
BECAUSE: in your code you say the condition of while loop is i should be equal to or greater than n. I guess Clavier.lireInt(); getting value from user. So if user enters 1 condition will be while( 1 <= 2) then it will go through the while loop. Increment the i, then i will be 3 again greater than n, increment i then 4 will be greater than n. It will go like that.
I thing your condition should be :
while(n>=i)
Then you can enter n as 5 and count i = 2 to 5.
Am I correct ?
Your number needs to be greater than 0 based on your if condition. To get into the while loop, your number needs to be less than or equal to 2 since you set i equal to 2. So your options are 1 or 2.
With that being said, once you're inside the while loop, you will never be able to exit (you have created an infinite loop) because n will always be less than i. Your i is incrementing by 1 on each loop iteration, and n is never changing, so it will never be greater than i. You should add a terminating condition (some way to exit the loop).
Provide 1 or 2 as Clavier.lireInt() and you will go inside the loop.
Example :
class Labo21 {
public static void main(String[] arguments) {
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = 1; //Clavier.lireInt(); //keyboard
if (n <= 0) {
System.out.print("ERROR");
} else {
i = 2;
somme = 1;
while (n <= i) {
System.out.println("in loop");
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
The title is pretty much self explanatory. :)
1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5
If it fits into an int/long, just check if the number modulo 10 is 0 and keep a counter:
long x = ...
if (x == 0) {
return 0;
}
int counter = 0;
while (x % 10 == 0) {
counter++;
x /= 10;
}
If it's too big to fit in long, store it in a String and count zeroes from the last char:
String s = ...
int counter = 0;
while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
counter++;
}
Integer class has an inbuilt function to count the trailing zeros.
javadocs
int trailingZeroes = Integer.numberOfTrailingZeros(int i);
Three lines:
int zeroes = 0
while(num%10 == 0 && num != 0) {
zeroes++;
num /= 10;
}
This uses the modulus operator. As long as we can divide by ten without remainder, increment the counter.
Here is another solution using Java 8 Streams:
int trailingZeros = String.valueOf(number).chars()
.reduce(0, (count, ch) -> (ch == '0') ? count + 1 : 0);
This transforms the number to an IntStream. This stream is then reduced using a lambda which resets a counter each time a non-zero char comes up.
You could always just use a regular expression:
Pattern pattern = Pattern.compile("(0+)$");
Matcher matcher = pattern.matcher(String.valueOf(123140000));
Integer trailingZeroes = 0;
if (matcher.find()) {
trailingZeroes = matcher.group(1).length();
}
System.out.println(trailingZeroes);
you can turn the int to a String and iterate in reverse, counting the zeros until you find a char that is not zero:
int countZeros(int x){
String a = Integer.toString(x);
int numOfZeros = 0;
for(int i = a.length() - 1; i >= 0; i--)
if (a.charAt(i) != '0') break;
else numOfZeros ++;
return numOfZeros;
}
Testing with :
System.out.println(countZeros(25000)); will print 3
System.out.println(countZeros(25)); will print 0
Hope this helps.
Not tried this code but this should work.
int counterForZeros=0;
for(long i=10;true;)
{
if(num%i==0)
{
counterForZeros++;
i*=10;
}
else
{
break;
}
}
System.out.println("Number of zeros in "+num+" is "+counterForZeros);
Well, if this is a contest to see who can do it in the fewest lines:
trailingZeroes = String.valueOf(num).length() - String.valueOf(num).replaceAll("0*$","").length();
I am trying to increment the counter by whatever number the user inputs. I have been at this for almost an hour now and cannot figure it out. Any ideas?
Here's what I have:
if (starting < ending) {
while (i < ending) {
++i;
System.out.println(i);
}
}
else if (starting > ending) {
while (i > ending) {
--i;
System.out.println(i);
}
}
else {
System.out.println(i);
}
No matter what increment is entered, it starts at the starting number and counts up or down by 1.
It counts up or down by 1 because of ++i and --i. The ++ and -- operators are equal to i = i + 1 and i = i - 1, or i += 1 and i -= 1 respectively.
In order to increase or decrease by the amount a user enters, use i = i + userInput and i = i - userInput, or i += userInput and i -= userInput.
For example:
int userInput = 4;
if(starting < ending) {
while(i < ending) {
i = i + userInput;
System.out.println(i);
}
// ... etc
}
In your while loop, you could put:
while (i > ending){
i -= numberUserInput;
}
This will reassign i's value with itself plus the variable that holds the number the user input (named whatever you want). For addition, you could use += instead of -=.