Answer to Exercise 4

OK, this should have been nice and easy! The only thing you need here is to use modulus 3 in an IF Statement. If a number can be divided by 3 with no remainder then you can increment a counter variable.

 

C# NET Answer

private void btnDivideByThree_Click(object sender, EventArgs e) {

	int counter = 0;

	for (int i = 1; i < 1001; i++)
	{
		if (i % 3 == 0)
		{
			counter++;
		}
	}

	MessageBox.Show(counter.ToString());
}

 

VB NET Answer

Private Sub btnDivideBy3_Click(sender As Object, e As EventArgs) Handles btnDivideBy3.Click

	Dim counter As Integer = 0

	For i = 1 To 1000
	    If i Mod 3 = 0 Then
			counter = counter + 1
	    End If
	Next

	MessageBox.Show(counter.ToString())

End Sub

 

Java Answer

package modulus_problem;
import javax.swing.JOptionPane;

public class Modulus_problem {

	public static void main(String[] args) {
        
		int counter = 0;
		for (int i = 1; i < 1001; i++)
		{
			if (i % 3 == 0)
			{
				counter++;
			}
		}

		JOptionPane.showMessageDialog( null, counter );
		System.exit(0);
	}
}