Skip to content

Instantly share code, notes, and snippets.

@datduyng
Forked from cbourke/conditionals-H.md
Created October 12, 2018 05:06
Show Gist options
  • Select an option

  • Save datduyng/985008f7875b49246836b88622b71084 to your computer and use it in GitHub Desktop.

Select an option

Save datduyng/985008f7875b49246836b88622b71084 to your computer and use it in GitHub Desktop.
auto-posted gist

Conditionals

CSCE 155H - Fall 2018

  • Normally, programs have sequential control flow
  • However, more complex problems require decisions
  • Conditionals are how we can make some code execute under some condition(s) and/or other, different code to execute under other conditions
  • if-statements, if-else statements, if-else-if statements
  • Conditionals rely on some logical condition

Basic If/Else-If/If-else-if

if(<condition>) {
  //the code inside this block will execute if and only
  //if the <condition> evaluates to true
}

if(<condition>) {
  //block A
} else {
  //block B
}

if(<condition1>) {
  //block A
} else if (<condition2>){
  //block B
} else {
  //block C
}

Numeric Comparison Operators

  • <, >, <=, >=
  • Equality operator: ==
  • Inequality operator: !=
  • All of these numeric comparison operators can operate on literals (fixed, hardcoded values), variables, or expressions
  • Work in both languages for the 3 basic types
int a;
double b, c;

if(a == 0) {
  //...
}

//alternatively you could, but shouldn't do:
if(0 == a) {
  //...
}

//compare values stored in two variables:
if(a == b) {
  //...
}

//you can also use expressions:
if(b * b - 4 * a * c < 0) {
  //...
}

//you can, but shouldn't: tautology
if(10 < 20) {
  //....
}

Negation operator

  • Any logical expression can be negated using a single !
  • (a == b) has a negation of !(a == b) but really should rewrite this as (a != b)
  • Ex: (a <= b) has a negation of !(a <= b) but really you should write (a > b)

Boolean Variables

  • Often, you'll want to use boolean variables (variables that can hold a truth value, either true or false)
  • In C: there are no boolean variables, there is no keyword "true" nor "false"
  • Instead: you use an int variable
    • False is always 0
    • True is anything else, ie any non-zero value (5, 3.5, -2, etc.)
    • But, the convention is to use 1 for true
  • In Java: you have a boolean variable type that can be assigned the values true or false
boolean isStudent;
isStudent = true;
isStudent = false;

if(isStudent) {
  System.out.println("You get a 20% discount!");
}

if(!isStudent) {
  System.out.println("You do not get a discount!");
}
int isStudent;
//set it to true:
isStudent = 1;
//set it to false:
isStudent = 0;

if(isStudent) {
  printf("You get a discount\n");
}

if(!isStudent) {
  printf("full price\n");
}

Logical Operators

  • You can combine logical statements to form more complex logical statements using "connectives" or logical operators
  • The logical AND is true if and only if both of its operands (sides) are true
    • Syntax: &&
    • Ex: a && b where a and b are expressions or variables, etc.
    • This is true if and only if a is true and b is true
    • It is false when either a is false or b is false or they are both false
  • The logical OR operator is true if at least one of its operands is true
    • Syntax: ||
    • Example: a || b
    • true if a is true or if b is true or if both are true
    • false when both a and b are false
  • Fact: !(a && b) (DeMorgan's Law) is equivalent to (!a || !b)
if(a > 10 && a < 20) {
  //a = 5: false
  //a = 15: true
  //a = 25: false
}

if(a == b && a < 10) {
  //a = 5, b = 5: true
  //a = 5, b = 10: false
  //a = 10, b = 10: false
}

if(a > 10 || a < 20) {
  //a = 5: true
  //a = 15: true
  //a = 25: true
}

if(a == b || a < 10) {
  //a = 5, b = 5: true
  //a = 5, b = 10: true
  //a = 10, b = 10: true
}

Pitfalls

  • Consider the following C code:
if(0 <= a <= 10) {
  ...
}
  • IN C, the above code will compile, and execute and will not work for certain values (ex: 20)
  • C will evaluate the first expression giving a value (say 1) and then the second expression, giving an overall true value
  • Solution:
if(0 <= a && a <= 10) {
  ...
}
  • In Java, the above mistake is not even possible: it is a compiler error

  • Consider the following code:

//C:
int a = 5;

if(a = 10) { ... }
  • The above will compile and run but give bad results

  • a = 10 is an assignment, which assigns the value of 10 to a and 10 is true, thus the condition will always evaluate to true

  • This mistake is not possible in Java

  • Keep an eye out for such things by using a good font!

  • Consider the following code:

if(a == 10); {
  printf("a is 10!\n");
}
  • An empty code block may or may not execute, but the code block in curly brackets is not bound to the conditional statement

  • Make your life easier in C: use gcc as a linter

    • Lint: not necessarily "dirt" (or syntax errors) but likely stuff in code that we don't want or didn't actually intend to have
    • gcc can be used as a simple linter using the flag -Wall (warnings, all of them)

Short Circuiting

  • Consider a logical and: a && b
    • If a evaluates to false, does it matter what the value of b is?
    • NO; since the first one is false, then whether or not the second is true does not matter, the entire expression evaluates to false
    • Neither programming language wastes time evaluating the second expression
  • Consider a logical or: a || b
    • If a evaluate to true, does it matter what the value of b is?
    • NO, the first being true, makes the entire statement true, so the second is irrelevant
    • Neither programming language wastes time evaluating the second expression
  • This called "short circuiting"
  • Why? Its more efficient to skip operations if you can.
  • Today: all languages still do this because of familiarity
  • Programmers expect this behavior and program toward it: they often use programming idioms to exploit it

Linters

  • In C, always remember to use the -Wall flag with gcc to catch "bad" code
  • In Java: don't ignore the warnings, take care of them

Non-numeric comparisons

  • In both languages, you can compare single char values
char initial = 'C';

if(initial == 'c' || initial == 'C') {
  //...
}
  • In neither language can you (or should you) use the == sign for other than numerical/or char values.
  • Ie: you cannot use == to compare strings in EITHER language
String a = "hello";
String b = "goodbye";
String c = "hello";

if(a == c) {
  //this will never be true
}
  • In both languages, == compares memory addresses not the contents
  • In both languages, you need to use a function (or method) to make such a comparison
  • In Java:
    • a.equals(b) (returns true if the contents of a and b are the same)
    • a.equalsIgnoreCase(b) (this disregards differences in upper/lower case)
    • a.compareTo(b): returns an int value that represents which string comes first (in ASCII/lexicographic order)
    • It is a comparator pattern: it returns
      • if $a &lt; b$ then it returns something negative
      • if $a = b$ then it returns zero
      • if $a &gt; b$ then it returns something positive
  • In C:
    • strcmp(a, b) is also a comparator pattern
    • It is included in the string libarary, #include <string.h>
    • Revisit this when we look at strings

Exercise:

Write a program that reads a decibel level from the user (using command line arguments) and gives the user a description of the sound level.

* 0 - 60 Quiet
* 61 - 70 Conversational
* 71 - 90 Loud
* 91 - 110 Very Loud
* 111 - 129 Dangerous
* 130 - 194 Very Dangerous
* < 0 or 195+










#include<stdlib.h>
#include<stdio.h>
int main(int argc, char **argv) {
//in c, the first command line argument is ALWAYS the executable file name
// argv[0] = "a.out"
//check for the correct number of CLA:
if(argc != 2) {
printf("Error: expected a decibel level\n");
exit(1); //exits with an error code of 1 indicating an error
}
//atoi converts an Alphanumeric string TO an Int
int decibel = atoi(argv[1]);
//for doubles: atof alphanumerc to float
if(decibel < 0) {
printf("Error: invalid decibel level\n");
} else if(decibel <= 60) {
printf("quiet\n");
} else if(decibel <= 70) {
printf("Conversational\n");
} else if(decibel <= 90) {
printf("Loud\n");
} else if(decibel <= 110) {
printf("Very Loud\n");
} else if(decibel <= 129) {
printf("Dangerous\n");
} else if(decibel <= 194) {
printf("Very Dangerous\n");
} else {
printf("Unknown value\n");
}
return 0;
}

Style

Variable Names

Rules: * They may contain a-z or A-z or 0-9 or _ * They may not begin with a number

Conventions:

  • In general, you should follow consistent naming conventions

  • underscore_casing_convention words are separated by underscores and all letters are lowercase

  • UPPERCASE_UNDERSCORE_CASING words are separated by underscores but all letters are uppercase (usually you use this with constants or macros defined using #define

  • More modern convention: camelCasingConvention no underscores, but each new word begins with a uppercase letter, the first word is lowercased and all other letters are lowercase (the best most modern convention)

  • Variables shoul have descriptive names

  • x, y, a, b are okay if you are describing x-y coordinates or coefficients, etc. but are poor variable names in general

  • Examples: initialValue, longitude, latitude, theta vs angleOfIncidence, latitudeDegree

  • In general abbreviations (or acronyms) are okay, but should be minimized

  • Code should be "self-documenting": code should express its meaning and intent

  • In general, avoid pluralizsations (unless it is an array or collection)

White Space

  • In general, compilers don't care about whitespace
  • Indention: 2 spaces? 3 spaces? a tab?
  • White space rules should be consistent
  • YOu can use tools (text editors will format automatically for you); or you can use tools to "clean up" your code
  • Example: https://www.tutorialspoint.com/online_c_formatter.htm
  • Indentation should increase with each nested code block: essentially treat like a bullet pointed list

Non-interactive input

  • For your first homework, all of your programs are interactive: the program prompts for input and a human user enters it, hits the enter key, etc.
  • The vast majority of programs are NOT interactive
  • You can instead use Command Line Arguments (CLAs)
  • When you run a program (say a.out) you can provide additional command line arguments:

./a.out 10 20 3.5 hello

  • In the above example, there are 5 command line arguments:
  • the first argument is always the executable file name (a.out)
  • Each is separated by a space
  • Each can be accessed using the argv in the main program (arg = argument, v = vector)
  • argc (argument count) tells you how many arguments were provided
  • Each argument can be accessed as follows:
    • argv[0] always the first argument (executable file name)
    • argv[1] would be 10
    • argv[2] would be 20
    • argv[4] would be hello
    • argc would have a value of 5
  • Each argument is a string, not a number
  • You can convert the string command line arguments to numbers using
    • atoi alphanumeric string to integer (int)
    • atof alphanumeric string to floating point number (double)

Exercise

  • Write a program to compute the roots of a quadratic polynomial using the quadratic formula. Initially, prompt the user for input, then update your program to use command line arguments. Be sure to handle all error conditions




















Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment