PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] Why is the number 30 not displayed at the end of the output?

 August 16, 2022     android, for-loop, intellij-idea, java, output     No comments   

Issue

enter image description here

package com.company;

public class Main {

    public static void main(String[] args) {
        // write your code here
        int p=0;

        for (int i=1; i<11; i++)
        {
            if (i%2 == 0)
            {
                System.out.println(p);
                p = p + i;
            }
        }
    }
}

Solution

Add a print after the loop. You can also start with 2. And increment by 2 for each iteration (thus eliminating the need for the modulo two test). Something like,

int p = 0;
for (int i = 2; i < 11; i += 2) {
    System.out.println(p);
    p += i;
}
System.out.println(p);

Which outputs

0
2
6
12
20
30


Answered By - Elliott Frisch
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing