User Tools

Site Tools


cs:c_language:boolean_expressions
Return to Home page

Boolean Expressions

Concepts:
Boolean expressions (and if statement)

Text:
Some examples regarding boolean expressions, in conjunction with the ifstatement.

Examples have been explained with comments in the code.

Solution:

boolean_expressions.c
/* Examples regarding boolean expressions */
 
#include <stdio.h>
 
 
int main() {
 
  int res;
  int x = 2, y = 3;
 
  /* In C, a number different than 0 is a TRUE value */
  if (-10) {
    printf("A: True\n");  /* Executed code */
  }
 
  /* A false condition in C is the number 0 */
  if (0) {
    printf("B: True\n");
  }else{
    printf("B: False\n"); /* Executed code */
  }
 
 
  res = 3+2*5; /* res=13 */
  if (res) { /* 13 is a True value */
    printf("C: True\n"); /* Executed code */
  }
 
  /* res that is equal to 13 is greater than the 7.
     The comparison is therefore a TRUE value, but
     NOT TRUE = FALSE */
  if ( !(res>5+2) ) {
    printf("D: True\n");
  }else{
    printf("D: False\n"); /* Executed code */
  }
 
  /* 2 > 5 is FALSE and 3 < 4 is TRUE, i.e,
     FALSE OR TRUE = TRUE, therefore the 
     variable res contain a value different 
     than 0, in this case it contains the
     value 1 */
  res = 2 > 5 || 3 < 4; /* 0 OR 1 */
  printf("E: %d\n", res); /* Print "E: 1" */
 
  /* x=2; y=3;
     2 >= 3 is FLASE, 3==3 is TRUE, 2!=3 is FALSE
     Analizing the boolean expression:
     (FALSE AND TRUE) OR NOT TRUE = FALSE OR FALSE = FALSE,
     therefore the variable res contains a 0 */
  res = (x >= y && x+1==y) || !(x!=y);
  printf("F: %d\n", res);
 
  return 0;
}

Output:
The output of this program is:

A: True
B: False
C: True
D: False
E: 1
F: 0

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/c_language/boolean_expressions
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/boolean_expressions.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy