Logical operations: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Java example.)
m (Added note about double equals.)
Line 40: Line 40:
}
}


Additionally, ^ is used for XOR.
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication).

Revision as of 22:01, 18 November 2007

Task
Logical operations
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses


Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments. If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.

C

void print_logic(int a, int b)
{
  printf("a and b is %d\n", a && b);
  printf("a or b is %d\n", a || b);
  printf("not a is %d\n", !a);
}

C plus plus

void print_logic(bool a, bool b)
{
  std::cout << std::boolalpha; // so that bools are written as "true" and "false"
  std::cout << "a and b is " << (a && b) << "\n";
  std::cout << "a or b is " << (a || b) << "\n";
  std::cout << "not a is " << (!a) << "\n";
}

Fortran

      SUBROUTINE PRNLOG(A, B)
      LOGICAL A, B
      PRINT *, 'a and b is ', A .AND. B
      PRINT *, 'a or b is ', A .OR. B
      PRINT *, 'not a is ', .NOT. A
      END

Java

...
public static void logic(boolean a, boolean b){
  System.out.println("a AND b: " + a && b);
  System.out.println("a OR b: " + a || b);
  System.out.println("NOT a: " + !a);
}

Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication).