logo

 

     
 
Home
Site Map
Search
 
:: Bitwise Courses ::
 
Bitwise Dusty Archives
 
 
 

rss

 
 

ruby in steel

learn aikido in north devon

Learn Aikido in North Devon

 


Section :: C

- Format For Printing...

A Little Course in C. Part 4 - Tests and Comparisons

Getting started with C programming
Wednesday 20 November 2013.
 

In your programs you will often want to assign values to variables and, later on, test those values.

For example, you might write a program in which you test the age of an employee in order to calculate his or her bonus. Here I use the ‘greater than’ operator > to test of the value of the age variable is greater than 45:

if (age > 45) {
   bonus = 1000;
}

Operators

Operators are special symbols that are used to do specific operations such as making comparisons between two values or adding and multiplying numbers. One of the most important operators is the assignment operator, =, which assigns the value on its right to a variable on its left. Note that the type of data assigned must be compatible with the type of the variable.

This is an assignment of an integer (10) to an int variable named myintvariable:

int myintvariable;
myintvariable = 10;

Assignment or Equality?

Beware. While one equals sign = is used to assign a value, two equals signs == are used to test a condition.

= this is the assignment operator.

e.g. x = 1;

== this is the equality operator.

e.g. if (x == 1)

Testing Values

C can perform tests using the if statement. The test itself must be contained within parentheses and it should be capable of evaluating to true or false. If true, the statement following the test executes. Option¬ally, an else clause may follow the if clause and this will execute if the test evaluates to false. Here is an example:

if (age > 45) {
        bonus = 1000;
} else {
        bonus = 500;
}

You may use other operators to perform other tests. For example, this code tests if the value of age is less than or equal 70. If it is, then the conditional evaluates to true and "You are one of our youngest employees!" is displayed. Otherwise the condition evaluates to false and nothing is displayed:

if (age <= 70){
        printf("You are one of our youngest employees!\n");
}

Notice that the <= operator means ‘less than or equal to’. It performs a different test than the < operator which means ‘less than’.


This course is based on my eBook, The Little Book Of C, which is provided with my multimedia online course, C Programming For Beginners.

Previous Lesson: Constants and #define

AddThis Social Bookmark Button


Home