Entering numbers in program using while loop - java

I am a beginner in Java, can somebody please explain me how the total is 11.
Question - The user is ready to enter in these numbers one by one until the program stops:
4 7 5 8 9 3 4 1 5 3 5
What is displayed as the total?
int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
}
System.out.println(total);

I'll explain step by step.
Step - 1:
You've declared two integer variables. One for holding the input, and another for holding the total value after your calculation. The integer total is initialized as 0. The following part of your code is doing this:
int number;
int total = 0;
Step - 2:
Now you're providing input values. Then the input values are entering the while loop. The while loop will continue to execute unless your input value is 1. Your first input is 4, 4!=1, so, it enters the loop.
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
Step - 3:
Now, inside your loop, you're checking whether your input value is less than 5 or not. If it's less than 5, then total value will be incremented to total + number. Else, total remains unchanged. Regardless of the if condition, your system will continue to prompt you to provide number inputs as long as it's not 1. The following code does this:
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
}
In this case, your input sequence is 4 7 5 8 9 3 4 1 5 3 5.
For first input 4, 4 < 5, which is true, so total = 0 + 4 = 4. The next input is 7, 7 < 5 is false, so total remains 4, same goes for inputs 5 through 9. When your input is 3, 3 < 5 is true, so total = 4 + 3 = 7. Then for input 4, 4 < 5 is true again, so total = 7 + 4 = 11
As we've already seen, the above while loop will terminate, as soon as you input 1. Your next input is 1, so the loop will terminate, you can't input any more number, and your final total value remains 11.
Step - 4:
Outside the loop, you're printing the value of total, so it will display 11.
System.out.println(total);
p.s.
If you understood my solution, your next task will be to do the exact same thing using for loop.

You are entering 4 7 5 8 9 3 4 1 5 3 5
The following code only allows 4 7 5 8 9 3 4 to be accepted cause it breaks from the loop when 1 is entered.
while (number != 1)
{
...
}
More over the following code only adds 4 3 4 because number should be less than 5
if (number < 5) total = total + number;
Hence you get 4 + 3 + 4 = 11

While loop will run till the user enters 1.
And the numbers will sum up if the number entered is less than 5.
So from what the user has entered, it will be 4+3+4 = 11. At 1, the while loop will exit.

int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
if (number < 5) total = total + number;
// only adds 4 3 4 because number should be less than 5
System.out.print("Enter a number");
number = input.nextInt();
}
System.out.println(total);
// Because of that you can: 4+3+4 = 11

your while loop will run until it gets 1 as input.
while (number != 1)
Inside while loop you have a if clause it will add your input to total when entered number is less than 5
if (number < 5) total = total + number;
that's why only adds 4, 3, 4 and total=11

Your input is 4 7 5 8 9 3 4 1 5 3 5
Your code snippet with explanation as comment is given below:
int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt(); // your first input number ie. 4 is taken as input
while (number != 1) // while starts because 4 > 1
{
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
/* in while loop only 4,3,4 will be added to the total because you have **if (number < 5) total = total + number;** loop will break after taking input 1 because of **while (number != 1)**. At that time total will be equal to 11. */
}
System.out.println(total); // outside loop value of total = 11 will be printed

Related

Looping with conditional statement

Hi i want to learn how to do java loop that will determined the number if it is an odd or even like
1st value: 8
2nd value: 15
output:
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
You can do it like so:
Scanner input = new Scanner(System.in);
System.out.print("First value: ");
int start = Integer.parseInt(input.nextLine());//Gets the first number
System.out.print("Second value: ");
int end = Integer.parseInt(input.nextLine());//Gets the second number
for(int i = start; i <= end; i++){
if(i%2==0){//When the number is divided by 2, it gives a remainder of 0. Modulus helps us get the remainder.
System.out.println(i+" is even");
}else{//Doesn't satisfy the first condition. It must be odd.
System.out.println(i+" is odd");
}
}
We use a Scanner to read the user input, then use a for loop and leverage modulus (%). Modulus calculates the remainder of a number after dividing it by a certain number. If a number divided by 2 gives a remainder of 0, that means it is divisible by 2. We can construct an if statement to check whether it is divisble.
Test Run
First value: 1
Second value: 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Hey you can use a for loop it's simple.
for(int i=8;i<=15;i++){
if(i%2==0){
System.out.println(i+"is even");
}else{
System.out.println(i+"is odd");
}
}
And I expect you know how to ask inputs so just pass it on the place of 8 and 15
The short version:
https://www.youtube.com/watch?v=cakN0XC6CcQ
Use number % 2 == 0 for even numbers.
The long version:
// Create a new Scanner() to scan System.in
Scanner scanner = new Scanner(System.in);
// Get the two inputs
int first = scanner.nextInt();
int second = scanner.nextInt();
// Start i as the first number
// While it is less than or equal to the second
// Add one each time
for(int i = first; i <= second; i++) {
// Is there a remainder from dividing i by 2?
// If no, it's even
boolean even = i % 2 == 0;
// Print it
System.out.println(i + " is even: " + even);
}
scanner.close();

Want to print a n*n matrix in zigzag pattern

This is my code:
class Main{
public static void main(String args[]){
System.out.println("Enter the value of N: ");
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int max = 0, min = 0;
if(n1<=50){
for(int i=1;i<=n1;i++){
for(int j=1;j<=n1;j++){
max = n1*i;
min = (max-n1)+1;
if(i%2!=0){
while(max<=min){
System.out.print(max);
max--;
}
}
if(i%2==0){
while(min<=min){
System.out.print(min);
min++;
}
}
}
System.out.println("");
}
}
else
System.out.print("Invalid Value of n1");
}
}
the problem is to print a zigzag matrix like
if we enter n=4 then the output should be like:
4 3 2 1
5 6 7 8
12 11 10 9
13 14 15 16
and if we enter 3 it should come like
3 2 1
4 5 6
9 8 7
now in the above code its going to a infinite loop
Considering it is most likely some kind of a homework, I won't hand you a solution as it takes away the learning process. Instead, I'll just give you some hints.
You need 2 nested for loops, the outer one for rows and the inner one for columns.
Find out what the max and min numbers in a given row are. They are connected to the row number.
If the row number is odd, start with the max number and go down. If it is odd, start from the min number and go up.

Re-running the program in the same run

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4.
Design the program such it allows the user to re-run the
program with a different inputs in the same run.
public void findLargestInteger(){
//create Scanner object
Scanner input = new Scanner(System.in);
int x;
do {
//prompt user input
System.out.print("Enter an integer, the input ends if it is 0:");
//declare variables
int n, countNeg = 0, countPos = 0;
float sum = 0;
//calculate how many positive and negative values, total, and average
while ((n = input.nextInt()) != 0) {
sum = sum + n;
if (n > 0) {
countPos++;
}
else if (n < 0) {
countNeg++;
}
}
//display results
if (countPos + countNeg == 0) {
System.out.println("No numbers are entered except 0");
System.exit(0);
}
System.out.println("The number of positives is " + countPos);
System.out.println("The number of negatives is " + countNeg);
System.out.println("The total is " + sum);
System.out.println("The average is " + (sum / (countPos + countNeg)));
}while ((x = input.nextInt()) != 0);
}
How can I get the prompt to display correctly at the end and keep it
running?
Output:
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0 The average is 3.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0
The average is 3.0
You could change while((x = input.nextInt()) != 0); to while(true); if you really want to keep repeating your program.
That IS an infinite loop though which is not really a good way to go.
So instead of looking for the next integer and compare with 0, maybe you should write something like
System.out.print("Do you want to quit? (y/n): ");
at the end of your loop (right before the while((x = input.nextInt()) != 0) line).
And then not check for 0 but for the y. At least then you don't have the program waiting for the user to input something without knowing what's happening.
Edit: Or you can just use a counter if you want to run it like twice or three times before it terminates ;)
Have you tried just calling your function inside a while loop?
public void findLargestInteger() {
// Your code
}
public static void main(String[] args) {
do {
findLargestInteger();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Would you like to continue? (0/1) ");
int n = reader.nextInt();
} while(n == 1);
}

How to get count value assign the table

I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
This is my code. and this is get from url in count value.
adltavailable = Integer.parseInt(count.get(i).toString());
for(int x =0; x<adltavailable; x++)
{
c = "Adultavailable";
category.add(c);
}
//Here is assign the table
int k = 0;
int size = category.size();
while(k < size)
{
for(int z=0; z<size; z++)
{
if(category.get(z).equals("Adultavailable"))
{
mycirimgs[k].setBackgroundResource(R.drawable.adultadd);
}
k++;
}
}
I get total seats value from url .And the value is assigned in table.If suppose i got 3 seats means I assign the table in 3 seats is not look like good.But this three seats assign 4 instead of 3.like wise.So I want the result If I get total seats 1 or 2 or 3 or 4 means I assign the table in 4 seats and 5 or 6 or 7 or 8 means I assign the table in 8 seats like wise. Thanks giving ur support.
I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
To round x to the next multiple of 4, write
(x + 3) & ~3
where + 3 rounds up and & ~3 clears the bottom two bits making it a multiple of 4.
To round up your input to the next multiple of 4, you can try the following:
Integer result;
if (input % 4 == 0) //Input is already a multiple of 4.
{
result = input
}
else // round up
{
result = ((input / 4) + 1)*4
}
Hope this is what you were looking for.

Is my understanding of this While Loop correct?

The example in the book asks the user to enter any positive number. Then the program will add the individual digits separately and print the total. For example if the user enters the number 7512 the program is designed to add 7 + 5 + 1 + 2 and then print the total.
I've written out the way I understand how the code works. Is this correct? Is my understanding of this loop correct with each step, or am I missing any calculations? What happens during the 4th loop when there is no remainder in 7 % 10?
1st run of loop ... sum = sum + 7512 % 10 which is equal to 2
n = 7512 / 10 which which equals to 751
2nd run of loop ... sum = 2 + 751 % 10 which is equal to 1
n = 751 / 10 which is equal to 75
3rd run of loop ... sum = 3 + 75 % 10 which is equal to 5
n = 75 / 10 which is equal to 7
4th run of loop ... sum = 8 + 7 % 10 <------?
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("This program will add the integers in the number you enter.");
int n = readInt("Enter a positive integer: ");
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
println("The sum of the digits is" + sum + ".");
}
}
The result of the operation 7 % 10 is 7, the remainder when you divide 7 by 10. The last iteration of the loop is to add 7 to the prior value. The next division step inside the loop (n /= 10;) takes n to 0, which is what ends the loop.
% is not the same as /
The % operator is for the modulus, not division... This means that the result of the operations is not dividing, but obtaining the remainder of the division, like:
7512 % 10 => 2
751 % 10 => 1
75 % 10 => 5
7 % 10 => 7
This kind of logic is fairly frequently used when dealing with numeric operations.
before run, sum = 0, n = 7512
1st run of loop ... sum = 0 + 2 => sum = 2, n = 751
2nd run of loop ... sum = 2 + 1 => sum = 3, n = 75
3rd run of loop ... sum = 3 + 5 => sum = 8, n = 7
4th run of loop ... sum = 8 + 7 => sum = 15, n = 0
After 7%10 you get 7 and that is added to your result.
And 7/10 will result in 0 and hence your loop ends and your sum now has addition that you want.

Categories

Resources