C Programming: Operators, Conditionals and Loops

Arithmetic Operators

+ adds, - subtracts, * multiplies, / divides (integer division discards the fractional part if both operands are integers), % gives the remainder (modulus), ++ increments by 1, -- decrements by 1.

Conditional (Relational) Operators

== equality, != not equal, > greater than, < less than, >= greater than or equal, <= less than or equal – each returns true or false.

Logical Operators

&& (AND) is true if both operands are non-zero/true; || (OR) is true if either operand is non-zero/true; ! (NOT) reverses the logical state of its operand.

Assignment Operators

= assigns the right-hand value to the left-hand variable. Compound operators +=, -=, *=, /=, %= perform an operation then assign the result, e.g. c += 5; is equivalent to c = c + 5;. Note the important distinction: a single = sets a value, while == compares two values.

Using Conditional Statements

Conditional statements determine TRUE or FALSE and act on the result – the most basic is the if statement. In C, TRUE always equals a non-zero number (returned as 1), while FALSE returns 0.

if (3 < 5)
    printf("3 is less than 5");

ELSE statements run if the IF is false; ELSE IF lets you chain multiple conditions into one code block:

if (age <= 12) {
    printf("You're just a kid!\n");
} else if (age < 20) {
    printf("Being a teenager is pretty great!\n");
} else if (age < 40) {
    printf("You're still young at heart!\n");
} else {
    printf("With age comes wisdom.\n");
}

The program is taken through each ELSE IF statement in turn until one condition matches; if none match, the final ELSE runs.

Loops

Loops repeat blocks of code until specific conditions are met, using the increment (++) and decrement (--) operators. There are three main types:

  • FOR loop: the most common type, requiring three conditions – initializing the variable, the condition to be met, and how the variable is updated, e.g. for (y = 0; y < 15; y++) { printf("%d\n", y); }.
  • WHILE loop: simpler, with only one condition, checked at the start – the loop runs as long as it’s true.
  • DO…WHILE loop: checks the condition at the end of the loop, so the loop body always runs at least once, even if the condition is false from the start.

Leave a comment

Your email address will not be published. Required fields are marked *

sponsors Ads