since few minutes I tried practice "using FOR loop with IF statement" to test user "Even Numbers"(divided / 2) in console screen, I wrote this trivial program to print the statement "IS even number" if the number divided by 2, and print "NOT even number" when not divided by 2, when I tried input a number like "1313" prints "IS even number" although it isn't even number..by calculater 1313/2 = 656.5 ... !
p.s. i want do that without using IF .. ELSE

This is my code:

// write some even numbers | loops and if statement
#include <iostream>
#include <process.h>
using namespace std;
int main()
{
	unsigned int n,j;

	cout << "Enter a number: ";
	cin  >> n;

	for(j=2; j<=n/2; j++)
		if(n%j==0)
		{
		cout << "IS even number" << endl;
		exit(0);
		}
	cout << "NOT even number" << endl;
	return 0;
}

Dani AI

Generated

The posted loop tests for any divisor of n (a simple composite check), not for parity. That explains the 1313 case: 1313 = 13 * 101, so a divisor exists and the loop hits the n%j==0 condition even though 1313 is odd. was pointing toward this logic mismatch; was right to flag the control-flow issue with exit(0).

A direct parity test is far simpler: check the remainder when dividing by 2. The remainder operator is defined in the language reference here. An even/odd result can be reported without an if/else by indexing a small message array (or using n & 1 for the low bit):

#include <iostream>

int main() {
    int n;
    std::cin >> n;
    const char* msg[2] = {"IS even number", "NOT even number"};
    std::cout << msg[n % 2] << '\n';
}

Notes and cautions:

  • exit(0) ends the whole process; for loop control use break, and for returning from main use return. The standard header for exit is <cstdlib> (documentation: https://en.cppreference.com/w/cpp/utility/program/exit).
  • Prefer signed int for general integer input unless unsigned behaviour is specifically required; negative input cast into unsigned can produce large values.
  • Integer division truncates any fractional part (e.g., 1313/2 as integers yields 656). That is unrelated to parity testing but can confuse expectations.

Short summary: replace the divisor-search loop with a parity check (n % 2 == 0 or n & 1) and avoid using exit(0) to control loop flow. This matches the intended “even number” test and avoids the misleading behavior seen with 1313.

Recommended Answers

All 2 Replies

Remove the exit(0); call.

It kills the entire program, not just the if (or the while).

Look up 'break' and 'continue' for more refined loop controls.

Try it with 9.

You will find it is also even because in the loop when j=3, n%j = 0

This loop has nothing to do with odd/even. Where did you get this code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.