CCPROG1_variables_operators
Tokens in C
Introduction to the Syntax of C
- C is a general purpose procedural programming language
- used to create operating systems like Unix and Windows, as well as other popular software applications
- the "words" in C are called tokens, and the "grammar" is called syntax
Tokens include...
Constants
- Numeric Constants/Literals
- Integers (whole numbers)
- ex. 1, -5, 12345
- Floating-point numbers (real numbers)
- ex. 2.55, -1234.0, 2.5e3 (same as 2.5 x 10^3)
- In defining numeric constants...
- No comma
- No space between the unary sign (+/-) and the digits
- Must begin and end with a digit - Character Constants/Literals
- A single letter or character that is enclosed in single quotes ('')
- ex.'a'
,'b'
,'+'
,'2'
(considered a character) - Special (Escape) Characters
\n
means newline\a
means alert\t
means tab\0
means null character\'
means single quote (useful inprintf
statements)%%
means percent symbol
- A single letter or character that is enclosed in single quotes ('')
String Literals
- A series of characters, should be enclosed in double-quotes ("")
- ex.
"This is a string with double quotes \" within. This is a \\ backslash in the string."
- ex.
Identifiers
- Descriptive names that are given to the variables, constants, and other entities in our program, can be used for variables and constants
- Defining identifiers...
- Must only consist of letters, digits, and underscores
- Cannot begin with a digit
- An identifier defined in the C standard library should not be redefined, keywords are also invalid identifiers
- keywords reserved in C:
for
,signed
,break
,if
(Geeks4Geeks: Keywords in C)
- keywords reserved in C:
- Case sensitive (
ans
≠ANS
≠aNs
≠Ans
)
- Variables
- These are entities that can store a value that can be changed during the execution of a program. The variable declarations tell the C compiler what type of data will be stored in each variable and how that data will be represented in memory
- Syntax:
<data type> <variable or variable list>
- Basic datatypes:
- Variables: Hungarian Notation (will be used in CCPROG1)
- Your variable names should start with/have a prefix if it's a certain datatype. They'll be checking this in your MCO (but it could be prof-dependent)
- This allows us to trace what data type a variable is
- Defining identifiers...
Data Type | Prefix | Valid Example |
---|---|---|
int | n | int nAge; |
long | l (lowercase L) | long lLong; |
float | f | float fTotal; |
double | d | double dAmount; |
char | c | char cJoke |
// --- IDENTIFIERS ---
my_variable // wrong: this is my var
input1 // wrong: tel#, 1stvariable, 7eleven, 200people
_MAX // wrong: money$
x //wrong input-number
for_loop_var // wrong: for
signed10 // wrong: signed
ans
ANS
aNs
Ans // these are all different
// --- VARIABLES AND HUNGARIAN NOTATION---
int nMyVariable, x, nMaxVal;
long var1, var2, var3;
float var4, varFive, varfive, fValue, fAverage;
double doubledouble, doubledoubledouble, DOUBLE, cFirstInit, cLast, ch1;
A series of Variables
A series of variables of the same type can be declared at the same time. Given that they are separated by commas and each list ends with a semi-colon. ;
We did this in the example above.
Define Constants
- These are entities that can store a value but cannot be changed. Usually, constant identifiers are written using all capital letters with underscores between each word
// --- DEFINE CONSTANTS ---
// These are usually at the start of the file.
#define SCHOOL "De la Salle University"
#define PI 3.14
#define MAX_STRING_LEN 50
#define LETTER_A 'a'
#define ANSI_RED "\e[0;31m"
#define ANSI_OFF "\e[0m"
Operators
- An operator is a symbol in C used to perform certain operations on values or variables.
Operator | Function |
---|---|
* |
multiplication |
/ |
division |
% |
modulo |
+ |
addition |
- |
subtraction |
More on Operators
Attempting to perform arithmetic operations on variables with different datatypes will give you a result of another type. Whatever is the "larger" data type that can hold both values becomes the "overall" or resulting datatype.
- Addition and Subtraction
- int
+/-
int = int (5 + 2 = 7) - int
+/-
float = float (5 + 2.0 = 7.0) - float
+/-
int = float (5.0 + 2.0 = 7.0) - float
+/-
float = float (5.0 + 2.0 = 7.0)
- int
- Multiplication and Division
- int
*/
int = int - int
*/
float = float - float
*/
int = float - float
*/
float = float
- int
- Modulo (Geeks4Geeks: Modulo Operator)
- Gives you the remainder (Geeks4Geeks: Modular Division)
- int % int = int (ex. 17 % 5 = 2, 1234 % 10 = 4, 0 % 2 = 0)
- Arithmetic precedence and associativity: In Natural Language, we read things left to right. Others, are right to left. Computers process things differently and some operators may have higher or lower precedence. If you're in CCPROG1, refer to the table below as you don't need all of them right now.
Operator | Description | Precedence | Associativity |
---|---|---|---|
() |
Parenthesis | 1 - Highest | Left-to-Right |
unary +/- |
Positive or negative sign | 2 | Right-to-Left |
* / % |
Multiplication Division Remainder/Modulo |
3 | Left-to-Right |
+ - |
Addition Subtraction |
4 - Lowest | Left-to-Right |
Sample Math Equations Conversion
You can try running this code in VsCode (If you have C installed), DevC++, or in an online C compiler like Programiz! (See installing a c compiler on windows for a guide.)
#include <stdio.h>
int main() {
int a, b = 3, c = 4, d = 5;
a = 2; // note I didn't have to put "int" again
int nFirstEquation = b*b - 4*a*c;
int nSecondEquation = (a+b)/(c-d);
float fThirdEquation = 1.0 / (1 + a * a);
int nFourthEquation = a * -(b-c);
printf("%d\n", nFirstEquation);
printf("%d\n", nSecondEquation);
printf("%f\n", fThirdEquation);
printf("%d\n", nFourthEquation);
return 0;
}
/* console output:
* -23
* -5
* 0.200000
* 2
*/
Assignment Operator
This lets us store a value or a computational result in a variable. In mathematics, we use = as "equals" to signify the left-hand side and right-hand side are equal. In programming languages like C, it's the assignment operator.
Declaration vs Assignment vs Initialization
Declaration is when you create a variable by doing <datatype> <variable name>;
without assigning it a specific value.
Assignment is simply giving the existing variable a value or expression. The syntax is <variable> = <expression>;
.
Initialization is when you declare and assign a value to it like so: <datatype> <variable name> = <value>;
The code above declared and initialized multiple variables. So in the example, we declared a variable a
. In the next line, we assigned it with a value of 2. We initialized b
, c
, d
, and nFirstEquation
up to nFourthEquation
with values and expressions. You can assign defined constants to variables as well. For example:
#include <stdio.h>
#define PI 3.1415926535
int main() {
float fMyPi = PI; // assign it to the constant we defined
printf("%f", fMyPi); // output as is would be 3.141593
return 0;
}
Note: It rounds up the 6th decimal point up. If we specified it to be printf("%.10f, fMyPi);
, it would print the entire thing.
Shortcuts
There are some shortcuts in C. It just makes everything cleaner. For example:
#include <stdio.h>
int main() {
int nMyInt = 2;
printf("nMyInt as is: %d", nMyInt);
nMyInt = nMyInt + 1;
printf("nMyInt when incremented the long way: %d", nMyInt);
nMyInt++;
printf("nMyInt incremented again using the short way: %d", nMyInt);
return 0;
}
/** console output:
* nMyInt as is: 2
* nMyInt when incremented the long way: 3
* nMyInt incremented again using the short way: 4
*/
You can use this for other operators as well.
Code | Equivalent To | Description |
---|---|---|
i = i + 2 |
i += 2 |
Add 2 to my variable i |
x = x-15 |
x -= 15 |
Subtract 15 to my variable x |
share = share/4 |
share /= 4 |
Divide variable share by 4 |
j = j % 2 |
j %= 2 |
Perform mod 2 onto variable j |
Keywords
Keywords have special meaning in C. These are reserved words that can't be used as identifiers. The common ones are: auto, else, long, switch, break, enum, register, typedef, case, extern, return, union, char, float, short, unsigned, const, for, signed, void, continue, goto, sizeof, volatile, default, if, static, while, do, int, struct, double.
If the Machine Project Specs/specifications were given to you at this point, then you might see that goto
is not allowed. goto
is a keyword that lets you jump to another part in your code. This isn't relevant to you now.
You may notice return 0;
in the code samples in this note. This is so you can end the program
Separators
Separators are symbols in C that are used to separate tokens. Spaces, tabs, and newlines (or whitespaces) are not tokens themselves. colon (:
), comma (,
), and semi-colon (;
) are also separators.
- They tell the compiler "This command ends here" or "This specific line of code ends here."
- Fun fact: The entirety of a C program can be done without tabs. It's guide to every line of code are these separators. No this doesn't apply to spaces. But, for example, this will still run:
#include <stdio.h>
int main(){int nSample = 42;printf("This is my code\n");printf("Hello World!\n\n\n\n");printf("My Sample Variable: %d\n",nSample);return 0;}
(doesn't mean you should do this though.)