1

I want to print numbers on label from 1-to 100

The number's sum must be dividing on 4.

Example:
print 35. because 3+5 = 8 .
8 dividing on 4.

This is code
from loop printing numbers. but how choose those numbers?
print those numbers from 1 to 100 ;

for (int i = 1; i < 100; i++)
{
     //select numbers wich sum is dividing on 4
     label3.Text += Convert.ToString(i) + " | ";
}
Daniel Laügt
  • 1,097
  • 1
  • 12
  • 17
refreshg
  • 35
  • 1
  • 9
  • Answer is in this link [Sum of digits in C#](http://stackoverflow.com/questions/478968/sum-of-digits-in-c-sharp) of StackOverflow. And 8 dividing 4 is 8%4 ==0 – Jose Luis Dec 30 '15 at 08:54

2 Answers2

3

Stolen from Greg Hewgill answer's, you can use his algorithm and use remainder operator (%) like;

int sum, temp;
for (int i = 1; i < 100; i++)
{
     sum = 0;
     temp = i;
     while (temp != 0)
     {
         sum += temp % 10;
         temp /= 10;
     }

     if (sum % 4 == 0)
     {
         Console.WriteLine(i);
     }
}

Result will be;

4
8
13
17
22
26
31
35
39
40
44
48
53
57
62
66
71
75
79
80
84
88
93
97

Here a demonstration.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

You should use a nested loop for that , and use the % operator (% means the rest of division):

for (int i = 1; i < 100; i++)
{
     for (int j = i; j < 100; j++)
     {
           //select numbers wich sum is dividing on 4
           if( (i+j)%4 == 0)
           {
                 label3.Text += Convert.ToString(i) + Convert.ToString(j) " | ";
           }
     }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52