Java - Expected output after a loop printing array [duplicate] - java

This question already has answers here:
Java Increment / Decrement Operators - How they behave, what's the functionality?
(2 answers)
Closed 7 years ago.
I've seen this question (from a multiple choice) "what is the output of the following program" :
class array_output {
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i/2;
array_variable[i]++;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
The expected output is:
1 2 3 4 5
It is clear to me that the value i is incremented twice, first in the body of the loop and at the last line.
But I don't really get what the line array_variable[i]++; is doing.
Any suggestions?
Thanks in advance to answer to this newbie question!

The post-fix increment and decrement operators return the value of a variable before altering its value. Consider the following:
int anInt = 0;
System.out.println("anInt: " + anInt);
// anInt: 0
System.out.println("anInt: " + anInt++);
// anInt: 0
System.out.println("anInt: " + anInt);
// anInt: 1
System.out.println("anInt: " + ++anInt);
// anInt: 2
System.out.println("anInt: " + anInt);
// anInt: 2
So basically, anInt++ returns the value of anInt before incrementing it. ++anInt increments the value of anInt before returning the (freshly-incremented) value.

array_variable[i]++; increments the value that is stored in array_variable[i] by one.

Related

How I can sum all numbers in array and print them as integer value in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
enter code hereI have this number "811218-3476"as string,I want to multiply 8 by 2,1 by 1, 1 by2, 2 by1 and so on as following:
8 1 1 2 1 8 3 4 7 6
2 1 2 1 2 1 2 1 2 1 *
16 1 2 2 2 8 6 4 14 7 ----> Result
My question is how I kan do sum for the result, I did sum one number with another number like
16 + 1+2+2+2+8+6+4+14+7 = 62,
but I want to do sum as following:
1+6+1+2+2+2+8+6+4+1+4+7 = 47.
I do not need you to write a code I have wrote it, but I want to know how I kan sum 1+6 instead of 16 as example. my code is here and it works fine.
I hope help know.
Thanks.
enter code here
public static boolean checknumber(String s) {
if(checkPersonNummer(s)== true) {
char [] charray = s.toCharArray();
int newch = 0 ;
int j = 0;
int i = 0;
String sum= "";
int x = 0;
for( j = 2; j < 8 ; j++) {
System.out.print(" "+ charray[j] + " ");}
for( j = 9; j < charray.length ; j++) {
System.out.print(" "+ charray[j] + " ");}
System.out.println(" ");
for( j = 2; j < 8 ; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
// System.out.println(" ");
for( j = 9; j < charray.length; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
System.out.print("\n--------------------------------------------");
System.out.println("");
for( i = 2;i < 8;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 2;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 1;
sum += newch;
}
System.out.print(newch + " " );
}
for( i = 9;i < charray.length;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 1;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 2;
sum += newch;
}
System.out.print(newch + " " );
}
System.out.println();
System.out.print("Total = " + sum);
}
return true;
}
}
This sounds like a homework assignment, and we're not a homework writing team. But I'll give you some basic advice.
First, I had one person tell me, "programming is the art of editing the null program until it does what you want". By that he meant that we start with a program that does nothing and slowly built it up.
That's a good way to start.
So... Start your program. You need to get your data in. Do that, and figure out how to print it.
After that, think about printing out each number times either 1 or 2 as your problem requires, and print each calculation as you go.
Then all you have to do is keep a variable outside of this loop to store the sum, and add each mini-calculation to it, then print it at the end.
Start small. Work up to the final answer. Lots of debug output while working on it.
Lets say I have an array of numbers [2,3,4,5,6], Think of this question as you are multiplying the numbers with 1 those are at odd position in the array and multiplying the numbers with 2 those are at even position in the array.
Answer to How to add 1 + 6 instead of 16
Check if the number is less than 10, if it is than you don't have to
worry about it But,
If the number is greater than 10 you can use the % operator.
For instance
15 % 10 gives you 5 and 15 / 10 gives you 1 that way you can separate two individual digits.

Int++ operator isn't increasing the int the first time it's ran [duplicate]

This question already has answers here:
Is there a difference between x++ and ++x in java?
(18 answers)
Closed 2 years ago.
Basically the goal of the program is to have the user input a number, increase is 3 times, then decrease it 3 times using unary operators. The issue is that when it's ran, the first "number is now ___" line ends up just showing the same number the user inputed rather than increasing it by one. New to Java, Don't really know why
import java.util.Scanner;
class U1_L4_Activity_One{
public static void main(String[] args){
int num;
Scanner startNum = new Scanner(System.in);
//Enter an int (num)
System.out.println("Enter starting number(must be an integer)");
num = startNum.nextInt();
//Increases num 3 times
System.out.println("number is now " + num++);
System.out.println("number is now " + num++);
System.out.println("number is now " + num++);
//Decreases num 3 times, back to original number
System.out.println("number is now " + num--);
System.out.println("number is now " + num--);
System.out.println("number is now " + num--);
}
}
The ++ unary operator can be used as a post-increment or pre-increment operator.
In this case, since you have added the ++ after the num variable, it is performing a post-increment operation.
This means that the num variable value is displayed first and then will be incremented by 1.
This is the reason the number is printed first and then incremented causing the same number to display again.
To fix this you can make use of the pre-increment operation.
System.out.println("number is now " + ++num); // <-- the num is incremented first and then displayed.
System.out.println("number is now " + ++num);
System.out.println("number is now " + ++num);
//Decreases num 3 times, back to original number
System.out.println("number is now " + --num); // <-- pre decrement operation
System.out.println("number is now " + --num);
System.out.println("number is now " + --num);
It's because num++ increments its value in the "background" and then returns it. If you want to increment num and immediatly return the value, you should use ++num.

Alternate between operations in a for-loop

I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}

How to represent a factorial programmatically [duplicate]

This question already has answers here:
print factorial calculation process in java
(3 answers)
Java factorial format
(2 answers)
How do I calculate factorial and show working?
(2 answers)
Closed 4 years ago.
I couldn't find a proper title.
I wrote a tiny program to calculate the factorial of a given integer. The program works fine as expected. Now I would like to also print its representation, say we have 4 as input, the program would output 24 and then print Because 4! = 4 x 3 x 2 x 1.
public class Test {
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
int i;
int fact;
int number= sc.nextInt();//Get user input and calculate its factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is " + fact);
System.out.println("Because " + number+"!" + " = " + number + "x" + (number - 1) ); // This is what I tried so far
}
}
The last println shows what I have tried. However, I'm only able to output 4! = 4 x 3, unable to go down to 1.

Java Array Error Array Table [duplicate]

This question already has answers here:
Java: getting a value from an array from a defined location
(3 answers)
Closed 5 years ago.
Why is this happening, why isnt it giving me *ThisIsWhatItShouldBe
Code
class ArreyTable{
public static void main(String OKM[]){
System.out.println("Index\tValue");
int px[] = {144,240,360,480,720};
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px);
}
}
}
cmd Result
Index Value
0 [I#7852e922
1 [I#7852e922
2 [I#7852e922
3 [I#7852e922
4 [I#7852e922
ThisIsWhatItShouldBe
Index Value
0 144
1 240
2 360
3 480
4 720
You're printing the entire array instead of the relevant element of it, which you can access by the [] operator:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
// Here ------------------------------^
}
In the code block
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px);
}
You are each time converting the array px to a string, which is [I#7852e922 for internal JVM reasons.
You have to indicate the index on the array:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
}
That will give the desired result.
Additionally you could replace the println with a printf:
for(int counter=0; counter<px.length; counter++){
System.out.printf("%2d: %3d%n", counter, px[counter]);
}
just change this line :
System.out.println(counter + "\t" + px[counter]);
So it will know what value to return ;)
You were originally printing the entire px array object. What was being printed was the output of the toString() function of the array object.
Object.toString() method returns a string, composed of the name of the class, an # symbol and the hashcode of the object in hexadecimal.
when you use px[counter], it references to the element value at that index.
Correct solution would be:
for(int counter=0; counter<px.length; counter++){
System.out.println(counter + "\t" + px[counter]);
}

Categories

Resources