I am new to computer programming. Could someone explain me this code...
s=0;
for(i=0;i<5;i++){
s=2*s+i;
}
And how did it have the output 0,1,4,11,26;
how did it have the output 0,1,4,11,26;
Did you take out the print statement? The code you posted doesn't output anything.
Have you written a small program and put that code in it and executed it?
To see what the code does add a println statement just after the for statement that prints out the value of s and the value of i.
If you have any questions about what is printed out, post the output here with your questions.
yeah, i actually shorten the code...
public class Hei{
public static void main(String[]args){
int s=0;
for(int i=0;i<5;i++){
s=2*s+i;
}
System.out.println(s);
}
}
I've run the program and the output was 26... Can you please explain why the output is 26.Thank you.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html They explain it well. For basic programming questions like these it's best to just google it.
at first i= 0 so the statement s=2*s+i = s it's like 0=2*0+0=0
next it goes to the code i++ which means i which is 0 will be added by 1 so now i becomes i=1
now it will be s=2*s+i = s means 0=2*0+1 =1 right? now the variable s will have a value of one and i again will go through i++ i then was 1 now will be incremented by 1 so it now becomes 2
now s=2*s+i =s means 0=2*1+2 it;'s 2*1=2 plus 2 equals 4 so now s=4 will be displayed that's it
Try this:
public class Hei {
public static void main(String[] args) {
int s = 0;
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
System.out.println(" s = " + s + " before the assignment statement");
s = 2 * s + i;
System.out.println(" s is now " + s + " after the assignment statement");
}
System.out.println();
System.out.println("Final value for s = " + s);
}
}
Better yet, take the original program and work it out step-by-step by hand, using a pencil and paper. You need to keep track of the current values of "i" and "s" at each step of the process.
Thanks for the explanation. It helped me a lot.
Thank you for the explanation. it is so helpful.
Create a java program to accept model of car and its price. The output should be name of car and its price on the road. Formula to calculate price on the road is Price on the road = car price + (sales tax ) +(eksesais duty). The program can repeat 3 times.
Price of car + Sales tax(% of price) + Eksesai duty(% of car price)
250000 and above 100% 20%
100000 to 249000 30% 10%
60000 to 99999 15% 5%
Below 60000 5% 0 %
Create a java program to accept model of car and its price. The output should be name of car and its price on the road. Formula to calculate price on the road is Price on the road = car price + (sales tax ) +(eksesais duty). The program can repeat 3 times.
...
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.