MIKUB IT



Jan. 25, 2021, 11:56 a.m.

C Stuff to remember





Here you find some C operators that you will use very often, while learning I was always looking what some of this stuff means.
So I just decided to make a small Blogpost about it so that I always know where I can look those operators and other stuff up.

C Shortcuts for incrementing and scaling variables


x++; //Increments x, Evaluates to x.
++x; //Increments x, Evaluates to x+1.

x--; //Decrement x, evaluates to x.
--x; //Decrement x, evaluates to x-1.

x+=3; //Add three to x.
x-=7; //Substract seven from x.
x*=2; //Multiply x by two.
x/=2; //Divide x by tw0.
x%=2; //Replace x with modulo.


C True or False definition


!x //Not x.
x == y //x equals y.
x != y //x is not equal to y.
x < y //x is less than y.
x <= //x is less than or equal to y
x || y //x or y.
x && y //x and y.
x > y || y >= z //x is greater than y or y is greater than or equal to z.


C trinary operator


The expression:
x ? a : b
evaluates to a if x is true, and to b if x is false.

### Example
#include
#include

int main(){
double x = 49;
printf("The truncated square root of x is %g.\n",
x > 0 ? sqrt(x) : 0);
}
The trinary conditional operator has a short-circuit(lazy) behavior:
if *x <= 0* , then sqrt(x) is never evaluated.


Variable placeholders and special characters


\n //New line.
\t //A tab.
%i //Insert an integer value.
%g //Insert a real number in general format.
%s //Insert a string of text here.
%% //Insert a plain percent sign.


While and for loop


#include

int main(){
int i = 0; //Declaring the variable i.
while (i < 10){ //Initializing the while loop.
printf("This is: Loop %i\n", i); //Prints which loop were at.
i++ //Increments i with each loop.
}
}

In the above example if *i* for example would be eleven, then the body of the while loop would be skipped. If we want a while loop to run at least once then there is the *do-while loop*.

Do while loop example

#include

void loops(int max){ //Declaring the max variable inside the loops function.
int i = 0;
do { //Tell the programm what to do.
printf("Hello you.%i\n", i);
i++;
} while (i < max); //Do it only as long as i is smaller than max.
}

int main(){
loops(3); //Prints "Hello you." three times.
loops(0); //Prints "Hello you." one time.
}



A while loop is made out of three parts.


- Initialize the variable *(int i=0)*
- Testing the condition *(i < 10)*
- Increment the variable *(i++)*


For loop example
The for loop uses the exact same steps as the while loop *(Initialize, test, increment)*, but encapsulates them in one place:


#include

int main(){
for (int i=0; i < 10; i++);{ //Initialize, test, increment.
printf("Hello you.%i\n", i);
}
}