0

Hi I'm currently in school for Computer science and I'm having problems with two of my codes, the first one pertains to the title. I have to create a program that takes only the odd digits of an input and sums them. I honestly have no idea how to approach this, this is all I have

Scanner in = new Scanner(System.in);

    int a;
    int b;

    System.out.println("Enter a number: ");
    a = in.nextInt();

    while (a > 0) { 
        if (a.charAt(0) % 2 != 0) {

        }
    }

the second problem I have trouble with is write program with loops that computes the sum of all square between 1 and 100 (inclusive) This is the code i have

    int i=1;
    int j=0;

    while (i<101){
      i = (i * i);
      j= (j+i);
      i++;
    }
    System.out.println(j);

Thanks, I've been searching through this book back and forth and found no ideas.

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
Jarod Wood
  • 1
  • 1
  • 4
  • 5

2 Answers2

0

I will not solve your home-work problem directly. But it will give you an idea what to do

Sum of all Odd numbers in given numbers

int sum = 0;
while(numbers are still there){
  if(presentNumber % 2 == 1){
     sum += presentNumber;
  }
}

and for second problem, if I understood correctly, Sum of Square Numbers which lies in 1 to 100

Logically, square root of 100 is 10. so all the square numbers which lies in 1 to 100 are 1 to 10 inclusive.

That's sum of squares of 1 to 10 numbers (1^2+2^2+3^2+...+10^2)

int sum = 0;
for(int I=0;i<=10;i++){
   sum += (i*i);
}
RaceBase
  • 18,428
  • 47
  • 141
  • 202
0

There are multiple way to approach the first option(odd / even numbers):

if ( x & 1 == 0 ) { even... } else { odd... } //This is because the low bit will always be set on an odd number.

or you can do something like:

boolean isEven(double num) { return (num % 2 == 0) }

Check Check whether number is even or odd for more option.

Now about the squares check out Fastest way to determine if an integer's square root is an integer for your answer

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
  • 1
    do we really need "Fastest way to determine ...". I think they are starter problems and bit of logic will do I guess :) – RaceBase Oct 10 '13 at 05:52