public class even_num{
public void addeven(){
int inputnum;
int total_even;
int ctr=0, even=0, x=0;
for(ctr=1; ctr<=10; ctr++)
{
System.out.print("Input a number: ");
inputnum=TextIO.getInt();
x=inputnum%2;
if(x==0)
even++;
}
System.out.println("Sum of all even numbers is " + total_even );
}
}
Adding even numbers using the for loop
Page 1 of 13 Replies - 4753 Views - Last Post: 22 September 2009 - 02:54 AM
#1
Adding even numbers using the for loop
Posted 21 September 2009 - 10:41 PM
Can someone help me with these... I am suppose to input ten numbers, and then add all the even numbers. I can only count the even numbers but not Add them. What should I do. Thanks!
Replies To: Adding even numbers using the for loop
#2
Re: Adding even numbers using the for loop
Posted 21 September 2009 - 11:18 PM
import java.util.Scanner; // program uses class Scanner
public class EvenAdd
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int[] count = new int[5];
int sum=0;
String[] str = new String[5];
for(int i = 0;i < str.length;i++)
{
str[i] = "";
}
for(int i = 0;i < count.length;i++)
{
count[i] = scanner.nextInt();
int j = 0;
if(count[i]%2 ==0 )
{
sum= count[i]+sum;
System.out.println(sum);
}
}
for(int i = 0;i < str.length;i++)
System.out.println(str[i]);
}
}
#3
Re: Adding even numbers using the for loop
Posted 22 September 2009 - 01:00 AM
here is a much simpler way of doing what you want, and more close to your original code:
[/quote]
public class even_num{
public void addeven(){
int inputnum;
int total_even=0;
for(ctr=1; ctr<=10; ctr++)
{
System.out.print("Input a number: ");
inputnum=TextIO.getInt();
if (inputnum%2==0)
total_even=total_even+inputnum;
}
System.out.println("Sum of all even numbers is " + total_even );
}
}
[/quote]
#4
Re: Adding even numbers using the for loop
Posted 22 September 2009 - 02:54 AM
Consider this one. =)
Good day.
public class even_num{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int total = 0;
int num;
System.out.println("Enter 10 numbers: ");
for(int i = 0;i < 10;i++){
num = scanner.nextInt();
total += (num % 2 == 0)?num:0;
}
System.out.println("The total is " + total);
}
Good day.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|