Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the loop after printing one?

Tags:

c

So here is the problem: Write a program that accept an integer n, print out the largest number but smaller or equal n that is the product of two consecutive even number. Example: Input: 12, Output: 8 ( 2x4 ) Here is my code :

#include <stdio.h>

int main()
{
  int n;
  scanf("%d", &n);
  for (int i = n; i >= 0; i--)
      {
        for (int j = 0; j <= n; j = j + 2)
            {
              if ( i == j * (j+2) )
                  {
                    printf("%d ", i);
                    break;
                  }
            }
      }
return 0;
}

So if i input 20, it will print out 8 and 0 instead of 8, if i input 30, it will print out 24,8 and 0 instead of just 24. How do i make it stop after printing out the first number that appropriate ?

like image 916
Quan Le Anh Avatar asked Dec 14 '22 07:12

Quan Le Anh


1 Answers

You need to stop an outer loop from processing, for example by using a boolean flag (meaning "solution found, we finish work") or a goto statement.

#include <stdio.h>

int main() {
  int n;
  scanf("%d", &n);
  int solutionFound = 0;
  for (int i = n; i >= 0; i--) {
      // this could also be put into for's condition i.e. "i >= 0 && !solutionFound"
      if (solutionFound) {
          break;
      }
      for (int j = 0; j <= n; j = j + 2) {
          if ( i == j * (j+2) ) {
              printf("%d ", i);
              solutionFound = 1;
              break;
          }
      }
  }
  return 0;
}

EDIT: immediate return as noted in the comments is also a nice idea, if you don't need to do anything later.

like image 192
Adam Kotwasinski Avatar answered Dec 15 '22 20:12

Adam Kotwasinski