User Tools

Site Tools


cs:c_language:boolean_expressions
Return to Home page

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cs:c_language:boolean_expressions [2019/02/26 14:35] (current)
Line 1: Line 1:
 +====== Boolean Expressions ======
 +**Concepts:​**\\
 +Boolean expressions (and ''​if''​ statement)
  
 +**Text:**\\
 +Some examples regarding boolean expressions,​ in conjunction with the ''​if''​statement.
 +
 +Examples have been explained with comments in the code.
 +
 +**Solution:​**\\
 +
 +<file C 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;
 +}
 +</​file>​
 +
 +**Output:​**\\
 +The output of this program is:
 +<code bash>
 +A: True
 +B: False
 +C: True
 +D: False
 +E: 1
 +F: 0
 +</​code>​

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?rev=1551188114&do=diff
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/boolean_expressions.txt ยท Last modified: 2019/02/26 14:35 (external edit)

Privacy Policy