3 Replies - 6947 Views - Last Post: 22 September 2009 - 02:54 AM Rate Topic: -----

#1 clive006  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-September 09

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!



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 );		
}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Adding even numbers using the for loop

#2 javafreak  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 97
  • Joined: 21-September 09

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]);
	   
	}
}

Was This Post Helpful? 0
  • +
  • -

#3 aks29921  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 84
  • View blog
  • Posts: 230
  • Joined: 24-August 09

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:
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]
Was This Post Helpful? 0
  • +
  • -

#4 AntonWebsters  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 88
  • View blog
  • Posts: 428
  • Joined: 15-August 09

Re: Adding even numbers using the for loop

Posted 22 September 2009 - 02:54 AM

Consider this one. =)
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.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1