C Programming Tutorial - Chapter 5

Tutorials involving the many programming languages: C, C++, Java, Perl, Python, etc...

C Programming Tutorial - Chapter 5

Postby Egaladeist on Wed Dec 19, 2007 10:20 am

Originally Posted by cgkanchi: here

C Programming Tutorial – Chapter 5

Operators in C

===========================
Things covered in Chapter 5
The mathematical operators (+, -, *, / and %)
The comparison operators (==, >, >=, <, <= and !=)
The logical operators (|| and &&)
The assignment operator (=)
The unary operators (++,--)
Bitwise operators (&, |, << and >> - very brief!!)
The ?: operator
===========================
Chapters 1, 2, 3 and 4 can be found at
http://tazforum.thetazzone.com/viewtopic.php?t=6453
http://tazforum.thetazzone.com/viewtopic.php?t=6454
http://tazforum.thetazzone.com/viewtopic.php?t=6455
http://tazforum.thetazzone.com/viewtopic.php?t=6456
respectively

In the last lesson we covered decision making and how to make the program do different things when different stuff happens. In this lesson, we will explore this theme a bit further.

First some theory. In C, several symbols have special meaning. We have already encountered two of them in the printf() and scanf() statements, % and \ . When evaluating mathematical and logical expressions (a + b is a mathematical expression while “is a greater than b” is a logical comparison), C uses symbols called operators. Let's have a look at some mathematical operators first...

Type this program into the editor and save it as mathop1.c. Compile, fix any errors and run it.
Code: Select all
/* mathop1.c
A program to demonstrate the use of mathematical operators
*/

#include <stdio.h>

void main()
{
   float a, b, c;

   printf("Enter a number: ");
   scanf("%d", &a);
   printf("\nEnter another number: ");
   scanf("%d", &b);

   c = a + b;   
   printf("\na + b = %d\n", c);
   c = a - b;
   printf("a - b = %d\n", c);
   c = a * b;
   printf("a * b = %d\n", c);
   c = a / b;
   printf("a / b = %.2f\n", a/b);

}


Let’s go over the code. The first line of interest is the line that says
Code: Select all
   float a,b,c;


The reason we use float is because we divide two integers later in the program. As you will know, the result of dividing two integers, isn’t necessarily an integer itself. For example, if I were to divide 3 by 4, the result would be ¾ or 0.75. Thus, a float is required to hold this result. The other thing you will notice that several variables are declared on the same line. As long as all the variables are of the same type, this is perfectly legal. You can even assign values to them like so:

Code: Select all
   float a,b,c=0, d=4.5;


In the above line, a and b are not assigned values while c and d are assigned the values 0 and 4.5 respectively.

The remaining code is fairly self-explanatory. Using the mathematical operators + (addition), - (subtraction), * (multiplication) and / (division), we add, subtract, multiply and divide two numbers.

Now let’s have a look at one last mathematical operator that is sometimes useful. It is called the modulo operator (represented by %) and what it does is, it divides one number by another and tells you how much is left over. For example, 34%10 gives you 4 because there are three 10s in 34 and there is 4 left over. So, in other words, the % operator gives you the remainder after the division is complete. Type this code into your editor and save it as mathop2.c.

Code: Select all
/* mathop2.c
A program to demonstrate the use of the %% operator
*/

#include <stdio.h>

void main()
{
   int a, b, c;

   printf("Enter a number: ");
   scanf("%d", &a);
   printf("\nEnter another number: ");
   scanf("%d", &b);

   c = a % b;
   printf("\na %% b = %d\n", c);

}

Again, the code is fairly self-explanatory. The % operator always results in an integer, so using int variables is enough in this case. The printf() statement contains two % signs because as you should remember from chapter 2, the % is a special character for printf() and it needs to be doubled up to be displayed. So now you know how to do simple arithmetic in C! Now, let’s look at comparison operators in C. C has 6 comparison operators, == (equal to), > (greater than), >= (greater than or equal to), < (less than), <= (less than or equal to) and != (not equal to). Type in the following code into your editor and save it as compare.c

Code: Select all
/* compare.c
A program to demonstrate the use of comparison operators
*/

#include <stdio.h>

void main()
{
   float a, b, c;

   printf("Enter a number: ");
   scanf("%d", &a);
   printf("\nEnter another number: ");
   scanf("%d", &b);

    if(a>b)
    {
       printf("a is greater than b\n");
    }

    else if(a<b)
    {
       printf("a is less than b\n");
    }

    else if(a==b)
    {
       printf("a is equal to b\n");
    }

}


Again, this code is fairly easy to understand. The other three operators work in exactly the same way. A useful exercise might be to try writing a program that utilises the other three operators.

There is another set of operators that you will use quite often when writing programs. These are called logical operators and are represented by && (logical AND) and || (logical OR). Basically, these are used to combine two or more comparisons. For example, if a is greater than b AND b is greater than c, then a is greater than c. In C, this would look like:

Code: Select all
if(a>b && b>c)
{
//do something
}

OR

if (a>b || b>c)
{
//do something
}


Type the following code into your editor and save it as logical.c.

Code: Select all
/* logical.c
A program to demonstrate the use of the logical && and || operators
*/

#include <stdio.h>

void main()
{
   int a, b;

   printf("Enter a number: ");
   scanf("%d", &a);
   printf("\nEnter another number: ");
   scanf("%d", &b);

    if(a>6 && b>6)
    {
        printf("Both a and b are greater than 6\n");
    }

    else if(a>7 || b>7)
    {
        printf("Either a or b or both are greater than 7\n");
    }
}


Compile, fix any errors and run. The main thing to notice here is that both the & sign and the | sign are doubled up (as && and ||). A single & or | sign is a completely different beast as far as C is concerned. One other thing to understand is that the || operator results in the condition being met if EITHER or BOTH of the expressions are true. So, in the above program, if BOTH a and b are greater than 7, the else if statement would still be true. The && operator is only met if BOTH expressions are true. Take a break now if you think you need it. We have two more classes of operators to deal with.

The next class of operator is very simple. It is called the assignment operator and represented by a single = sign. Basically, it is used to assign a value to a variable. We have been using it since chapter 2 whenever we declare variables like so:

Code: Select all
int a = 40;


The next set of operators is called the unary operators. They are so called because they only require one value (all the others require two, a+b for example means that the + operator requires two values to function) There are two of them, and all they do is, given a variable, add or subtract 1 from it. An example of this is:

Code: Select all
int a = 1;
a++;  //this adds 1 to the value of a, so a is now 2
a--;   //this subtracts 1 from the value of a, so a is now 1 again


Note that the lines in the above example are equivalent to:

Code: Select all
int a = 1;
a = a + 1;  //Yes, this is legal, but a++ is the preferred notation
a = a - 1;


You will encounter these two operators in an actual program in the next chapter.

There is a related series of operators in C represented by+=, -=, *= and /=. Essentially, the number on the right of the operator is added subtracted multiplied or divided with the variable on the left. An example of these is

Code: Select all
int a = 2;
a+=50; //a is now 52
a -=1; // this is equivalent to a--. a is now 51
a*=2; //a is now 104
a/=17; //a is now 6


Again, just like the unary operators, these are equivalent to

Code: Select all
int a = 2;
a = a + 50; //a is now 52
a = a - 1; // this is equivalent to a--. a is now 51
a = a * 2; //a is now 104
a = a / 17; //a is now 6


Phew! Now the stuff you need to learn in this chapter is over. However, I should mention some more operators (OK, so I lied…). One set of operators is called binary operators and messes with binary stuff. They are (&, |, >> and <<). Note the single & and | and the double > and <. You don’t need to know about this stuff now (and hopefully, you never will). The final operator is called the ?: operator and is just a shorthand way of writing an if statement. Again, hope you never encounter this (though I will cover it at some point in the series).

OK, that’s pretty much it for this chapter. Phew! It was a long one wasn’t it? Now go get yourself a drink and pat yourself on the back for a job well done (you did do it well, didn’t you?). We’ll cover something called loops in the next chapter and your mind better be well rested for it. I would also suggest you go through this chapter again, because we’ll be using quite a few of the operators from this chapter in the next one. As usual, if you have any questions, don’t hesitate to ask.

Cheers,
cgkanchi
User avatar
Egaladeist
Site Admin
 
Posts: 270
Joined: Fri Dec 14, 2007 1:12 pm

Return to Programming Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest

cron