Saturday, August 29, 2020

"Parity" is just a fancy way to saying "is a value even or odd"

[Source: harvard, cs50]


float.c : get a floating point number from the user

#include <cs50.h>
#include <stdio.h>

int main(void)
{

float price = get_float("what is the price?\n");

printf("the price plus tax is %f\n", price*1.0625);

}


limit the output to 2 digits after the decimal point:

#include <cs50.h>
#include <stdio.h>

int main(void)
{

float price = get_float("what is the price?\n");

printf("the price plus tax is %.2f\n", price*1.0625);

}



[Source: harvard, cs50]

int.c : get an integer from user

#include <cs50.h>
#include <stdio.h>

int main(void)
{

int age = get_int("What's our age?\n");
int days = age*365;
printf("You are at least %i days old\n", days);

}



better design:

#include <cs50.h>
#include <stdio.h>

int main(void)
{

int age = get_int("What's our age?\n");

printf("You are at least %i days old\n", age*365);

}



you can even do this: (but in terms of design, this may reach an inflection point at which the code becomes too hard to read)

#include <cs50.h>
#include <stdio.h>

int main(void)
{

printf("You are at least %i days old\n", get_int("What's your age?\n")*365);

}


[Source: harvard, cs50]


place holders: %s, %c, %f, %i, %li

%s     string

%c     char

%f      float, double

%i      int

%li     long



get_string, get_char, get_int, get_long, get_float, get_double, ...

the cs50 library provides these functions

these are all functions that will prompt the human user for certain values


Data types in C: bool, char, double, float, int, long, string

bool  (true or false)
char  (a single character, not two or more)
int   (an integer; it has a certain size; you can only count up to a certain size number with int, typically
         4 billion)
float   (floating point number, which is a fancy way of saying a real number [something that has a
            decimal point])
double   (just a real number that can have even more digits after the decimal point)
long   (uses more bits so can count higher than int; companies like Facebook and Google have more
           data than 4 billion, so they may need these types of numbers)
string   (one or more characters inside double quotes " " )
...
.
.
.
[source: harvard, cs50, david malan]


Repeat 50 times: for ( int i=0 ; i < 50 ; i++ ) { }

for (int i=0; i<50; i++)
{
printf("hello, world\n");
}



....... the syntax of the "for loop" is a little more funky (than the while loop), but the for loop is more succinct while achieving the exact same thing


[Source: Harvard, CS50]



Repeat 50 times: while ( i < 50 ) { }

int i=0;

while (i<50)
{

printf("hello,world\n");

i++;

}


while(true) { } = "forever loop"

this is the same as saying:

while (2==2)
{

}