new guy in this sphere, dont bash too much :S

#include <iostream>
using namespace std;

int main()
{
	int x,y;
	cin>> x; cin>> y;

	if (x==0) cout<< "x = 0";
         else cout<< "x isnt 0";
		return 0;
}

this piece works ok but if i add 1 more condition it fails:

#include <iostream>
using namespace std;

int main()
{
	int x,y;
	cin>> x; cin>> y;
	if (x==0);(y==0); cout<< "x/y = 0";
		else cout<< "neither is 0";
		return 0;
}

i want it to check if either x or y equals 0
so what can be done about this?

Dani AI

Generated

Quick diagnosis: the second snippet fails because of stray punctuation, not because you need a mysterious new keyword. The token sequence if (condition); makes the if body an empty statement. Anything after that runs unconditionally, so the else no longer pairs with the intended if and the compiler will complain. had that symptom; pointed you in the right direction with logical operators, but the semicolon issue is the common beginner trap.

To check "either x or y equals zero" use a logical OR. For example, use if (x == 0 || y == 0) (braces around the body are recommended). If the intent is "both are zero" use logical AND (&&) instead. A compact alternative for integers is if (!x || !y) which tests zero via boolean negation.

A few practical tips and cautions:

  • Always put braces { ... } even for single-line if bodies. It prevents bugs when editing later.
  • Beware = vs == mistakes. Turn on compiler warnings (GCC/Clang -Wall -Wextra) and treat warnings as errors during development.
  • If you plan to divide, check the divisor first. Logical operators short-circuit: if (y != 0 && x / y == 0) avoids a division-by-zero because the right-hand expression is evaluated only if y != 0.
  • Read the exact compiler error message; "else without if" or similar usually points to a stray semicolon or unmatched braces.

Checklist to fix the posted code: remove the stray semicolons after if(...), pick || or && according to the logic you want, add braces, and recompile with warnings enabled.

Recommended Answers

All 2 Replies

You write it like this:

int main()
{
  int x, y;
  cin >> x;
  cin >> y;
  if (x==0 && y==0)
  // the && means and, use || for or
  {
    cout << "x/y = 0";
  }
  else
  {
    cout << "neither is 0";
  }
  return 0;
}

thanks

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.