Shreyas Pednekar
Shreyas Pednekar

Reputation: 1305

Print multiple of 7 between 53 to 96

I want to print multiple of 7 between 53 to 96

Code:

int tbl = 0;
while(!(tbl > 53) || !(tbl < 96))
{
   tbl = tbl + 7;
   while(tbl > 53 && tbl < 96)
   {
      Console.WriteLine(tbl);
      tbl = tbl + 7;
   }
}
Console.ReadLine();

Output:

output

Output should be: 56, 63, 70, 77, 84, 91 It should stop at 91, but it is not stopping at 91

Upvotes: 0

Views: 378

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Since we want to print out every 7th item, for loop seems to be the simplest choice:

int start = 53;
int stop = 96;

for (int tbl = (start / 7 + (start % 7 == 0 ? 0 : 1)) * 7; tbl < stop; tbl += 7)
   Console.WriteLine(tbl);

Console.ReadLine();

If 53 value is fixed we can precompute the start value: (53 / 7 + (53 % 7 == 0 ? 0 : 1)) * 7 == (7 + 1) * 7 == 56:

for (int tbl = 56; tbl < 96; tbl += 7) 
  Console.WriteLine(tbl); 

Console.ReadLine();

Upvotes: 0

Dusan Radovanovic
Dusan Radovanovic

Reputation: 1679

This is the best and the fastest way to do this, when you hit a number which is divisible by 7, you continue to increment by 7 not by 1

int tbl = 53;

while  (tbl < 96)
{
   if (tbl % 7 == 0){
      Console.WriteLine(tbl);
      tbl+=7;
      continue;
   }
   tbl++;
}

Upvotes: 3

kunquan
kunquan

Reputation: 1267

It need to be && in the first while loop instead of ||

Upvotes: -1

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

Very basic approach

int tbl=53;
while  (tbl < 96)
{
   if (tbl % 7 == 0)
      Console.WriteLine(tbl);

   tbl++;
}

Upvotes: 4

Related Questions