C-Programming

Operators and types

Operators are nothing but are the symbols which are used to derive certain operations. An operator is a symbol which tells the computer to do certain mathematical or logical task. Operators are used in programs to manipulate and compute the data and variables. Therefore, operators are sometimes called as the driver of the operation. C contains large number of the operators.

Depending upon the type of operator, operators are classified into numbers of categories among them some important categories are as follows:

1. A) Binary Operator:
1. Arithmetic operators
2. Relational operators
3. Logical Operators
4. Assignment operators
5. B) Unary operators:
6. Increment and decrement operators
7. Unary minus operator
8. C) Conditional operator

Binary operators:

The word binary represents the meaning of this type of operator. Binary means “two” therefore that type of operator which takes two operands to compute the operation is called binary operators. There are many types of the binary operators among them some are explained below:

1. Arithmetic Operators:

C includes all the fundamental arithmetic operators. The symbol which is used to manipulate the various type of the arithmetic operation is called arithmetic operator. The arithmetic which are available in C are listed below:

 Operators Meaning Example + Addition a + b - Subtraction a – b * Multiplication a * b / Division a / b % Modulo division/ remainder operator a % b

It should be noted that, modulo division (%) is only possible between two integer but all other arithmetic operators can operate with float and double also.

Example: use of the arithmetic operators

/*write a program which uses all the arithmetic operators.*/

#include<stdio.h>

#include<conio.h>

void main()

{

int a,b,sum,sub,mul,mod;

float div;

clrscr();

printf("Pliz enter the value of a:\t");

scanf("%d",&a);

printf("\nPliz enter the value of b:\t");

scanf("%d",&b);

sum=a+b;

sub=a-b;

mul=a*b;

mod=a%b;

div=(float)a/b;

printf("\n sum of the given numbers %d and %d is %d", a,b,sum);

printf("\n difference between given nnumbers is %d",sub);

printf("\n multiplication of given numbers is %d",mul);

printf("\n remainder after dividing the %d by %d is %d",a,b,mod);

printf("\n division of given numbers is %f", div);

getch();

}

Out put of the program:

Pliz enter the value of a: 12

Pliz enter the value of b: 5

Sum of the given numbers 12 and 5 is 17

Difference between given numbers is 7

Multiplication of the given numbers is 60

Remainder after dividing the 12 by 5 is 2

Division of given numbers is 2.400000

Here in the program we are written the statement div= (float) a/b; because here div is a variable of float type but a and b are variables of type int. While dividing int by int it also produces the result in int i.e. it neglects the fractional part of the result and prints only 2.000000 which is wrong result. For this we have to tell the computer that the result is float, therefore we are writing float in front of the expression a/b. This process is called type caste because here we change the caste of the result of the program first the result was int further we change it into float.

/*Write flow chart and program code which converts the Fahrenheit temperature into the Celsius degree.*/

Program code:

#iclude<stdio.h>

#include<conio.h>

void main()

{

flaot faren,cel;

printf(“\nplease enter the temperature in Fahrenheit degree:\t”);

scanf(“%f”,&faren);

cel=(faren-32)*100\180;

printf(“\n\nthe given temperature in Celsius degree is %f.”,cel);

getch();

}

1. Relational operators:

The symbols which are used to compare two expressions or values or data are called relational operators. The result of the comparison is either true or false which is used to make a certain decision. If the relational expression is true then it returns one otherwise if the expression if false then it returns zero. C supports six relational operators which are as follows:

 Operator Meaning Example < Is less than X Is greater than X >Y >= Is greater or equal to X >= Y = = Is equal to X==Y != Not equal to X ! =Y

Note: When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will be evaluated first and then the result is compared. That is, arithmetic operators have a higher priority than relational operators. Relational operators are used in decision making statements such as if and while to decide the course of action of a running program. On these topics we study in next chapter.

Example of use of relational operator:

/*write a program that finds out the greatest number between two given integer.*/

#inlcude<stdio.h>

#include<conio.h>

void main()

{

int a,b;

printf(“please enter the value of a:   “);

scanf(“%d”,&a);

printf(“\nenter the value of b:  “);

scanf(“%d”,&b);

if(a>b)

pritnf(“\n%d is greater than %d.”,a,b);

else

pritnf(“\n%d is greater than %d.”,b,a);

getch();

}

sample output of the program:

please enter the value of a:  12

enter the value of b:   10

12 is greater than 10.

1. Logical operators:

If we have to combine two or more relational operations into a single expression then we use a logical operator which evaluates either true or false. Since it combines more than two relational expressions therefore it is also called compound relational operator. There are mainly three types of the logical operators which are:

&&    meaning logical AND

||        meaning logical OR

!        meaning logical NOT

The AND and OR operators are widely used but NOT operator is rarely used. Therefore we are not going to study this operator in detail.

If 1 represents true and 0 represents false then truth table of these operators will be as:

 X Y Z=X &&Y 0 0 0 0 1 0 1 0 0 1 1 1
 X Y Z=X ||Y 0 0 0 0 1 1 1 0 1 1 1 1

Table: truth table of AND operator                            Table: truth table of OR operator

From truth it is clear that in the logical AND operator if all the expressions are true only then it produces true result other wise result will be false. Similarly in case of logical OR operator if at least one expression is true then it produces true result. It produces false result only when all the expressions are false. Therefore in the case where all the conditions should be true then we have to use logical AND operator and the case where at least one condition is to be true then we have to use logical OR operator.

Examples:

/*Write a program that checks whether the number entered by the user is exactly divisible by 4 but not by 11.*/

TIPS: Before writing the code for this program we should know type of the operator is to be used. For this, problem should known very clearly. In this problem both the conditions mentioned (number is should be divisible by 4 and number should not be divisible by 11) must be true. Therefore in this case we have to use logical AND operator.

Source code:

#include<stdio.h>

#iclude<conio.h>

void main()

{

int number;

scanf(“%d”,&number);

if((number%4==0)&&(number%11!=0))

printf(“\n%d is exactly divisible by 4 but not by 11.”);

else

printf(“\nThe condition is false,”);

getch();

}

Sample output:

12 is exactly divisible by 4 but not by 11.

The condition is false.

/*write a program which find out whether the given year is leap year is or not. */<Bex> [6] marks

Before writing the code for this problem, we should know what type of year is called leap year or what is leap year? Leap year the year which is perfectly divisible by 4 but not by 100 or those year which is perfectly divisible by 400. Before writing the code for any program we should know the problem i.e. definition of the problem, what is the problem and what are the logic should be implemented to solve that problem. Only then we can write the proper program.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

{

int year;

scanf(“%d”,&yeat);

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)       printf("%d is a leap year\n", year);   else       printf("%d is not a leap year\n", year);

getch();

}

In the program the conditions year % 4 == 0 and year % 100! = 0 should be true. Therefore they are combined by the logical AND (&&) operator. In solving this problem another condition year %400==0 also valid. It means either upper condition or lower condition, both conditions are applicable to check whether the year is leap year or not. Therefore these conditions are combined by the logical OR (||) operator.

4. Assignment Operator:

The name of operator “assignment” says it is the operator which assigns something for a variable. Simple equal to sign (=) is called assignment operator which assigns a value or expression for a variable. It should take care that double equal to sign (= =) and assignment operator (=) are not same.

Example:

a=b+c;

b=a%b;

x=10;

y=’a’; etc.

C shorthand:

C has a set of shorthand assignment operators. Shorthand assignment operator is the combination of two different arithmetic operators. The assignment of shorthand takes the form:

Vao=exp;

Where v represents variable, ao represents arithmetic operator and exp represents expression. Here Vao=exp; is equivalent to V=V ao exp;

Different types of shorthand operators are listed in the table:

 Short hand Equivalent meaning A+=B; A=A+B; A-=B; A=A-B; A*=B; A=A*B; A/=B; A=A/B; A%=B; A=A%B;

Unary operator:

Unary means one. Therefore that type of operator which takes only one operand is called unary operator. There are different types of unary operators among them some important are as follows:

Increment and decrement operator:

The operator which increases the value of a variable by unity is called increment operator and the operator which decrease the value of variable by unity is called decrement operator. Increment operator is ++ and decrement operator is --. The increment operator ++ adds 1 to its operand where as the decrement operator – subtracts 1 from its operand.

Eg. i++; which is equivalent to i=i+1; and i--; which is equivalent  to i=i-1;

The unusual aspect is that ++ and -- may be used either as prefix operators (before the variable, as in ++n), or postfix operators (after the variable: n++). In both cases, the effect is to increment n. But the expression ++n increments n before its value is used, while n++ increments n after its value has been used. This means that in a context where the value is being used, not just the effect, ++n and n++ are different. If n is 5, then

x = n++;

sets x to 5, but

x = ++n;

sets x to 6. In both cases, n becomes 6.

NOTE:       The increment and decrement operators can only be applied to variables; an expression like (i+j)++ is illegal.

To understand this matter let’s take an example:

#include<stdio.h>

#include<conio.h>

void main()

{
int a=5,b;

b=a++;

printf(“\nb=%d”,b);

b=++a;

printf(“\nb=%d”,b);

getch();

}

output of this program will be:

b=5

b=7

Explanation of the program: In the program at first 5 is assigned to a. The statement b=a++; firstly assign the value of a and then increases the value of a by 1. Therefore 5 is stored on b and value of a will be 6 and b=5 will be printed. But in the statement b=++a; firstly value of a is increased by 1 i.e. value of a will be 7 which further assigned to b. therefore value of b will be 7 and hence b=7 will be printed.

Unary minus sign:

This is simply minus sign which changes the value of variable with negative. In the binary minus i.e. in arithmetic minus sign it takes two operands which subtract the second operand from first one but in the case of unary it takes only one operand. For example:

-n; is a statement.

C) Conditional operator (ternary operator? :):

This is different type of operator. It is combination of if – else statement as a condition operator. Therefore it is also called conditional statement. The statements

if (a > b)

z = a;

else

z = b;

compute in z the greatest of a and b. The conditional expression, written with the ternary operator ``?:'', provides an alternate way to write this and similar constructions. The general syntax of this type of expression is:

expr1? expr2: expr3

Here the expression expr1 (here which is conditions) is evaluated first. If it is non-zero (true), then the expression expr2 is evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated not both at a time. Thus to set z to the maximum of a and b,

z = (a > b)? a: b;

The conditional operator takes three operands; therefore we can not say that it is a binary operator, it is ternary operator.

It should be noted that the conditional expression is indeed an expression, and it can be used wherever any other expression can be. If expr2 and expr3 are of different types, the type of the result is determined by the conversion rules. For example, if f is a float and n an int, then the expression

(n > 0) ? f : n

is of type float regardless of whether n is positive. Parentheses are not necessary around the first expression of a conditional expression, since the precedence of ?: is very low, just above assignment. They are advisable anyway, however, since they make the condition part of the expression easier to see.

Write a program that finds out the greatest number among two numbers using conditional operator.

#include<stdio.h>

#include<conio.h>

void main()

{
int a,b;

int greater;

printf(“Please enter any two numbers:   “);

scanf(“%d%d”,&a,&b);

(a>b)? greater = a : greater = b;

pritnf(“\n\ngreater number is %d”,greater);

getch();

}

Explanation of the program:

In this program if a is greater than b then it assigns a as  greater otherwise b is assigned to greater. And finally greater in which is greatest number is assigned is printed.

Among these operators which are mentioned there are other types of operators are also available in C program such as bitwise operator, special operators (sizeof operator, pointer operator, comma operator, member selection operator etc). But important operators are explained above. Therefore we are not going to study other operators.

Precedence and Associativity of operators in C:

Each operator in C has its own precedence associated with it. The Precedence means in the expression containing more than one operator, which one is evaluated first and then after. There are distinct levels of precedence and operator belongs to one of the level. The operators at higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left or from right depending from the level. This is known as Associativity of an operator.

Precedence of Arithmetic operators and unary operators:

 Operators Associativity Precedence ++ , -- Right to left Highest - (unary minus) left to right * ,/, % Left to right + , - Left to right Lowest

Precedence of Relational operators and Logical operators:

 Operators Associativity Precedence ! Right to left Highest > , >=,< ,<= left to right = =, != Left to right && Left to right || Left to right Lowest

Summary of precedence of operators:

 Operators Associativity Precedence () [] -> . left to right Highest ! ~ ++ -- + - * (type) sizeof right to left * / % left to right + - left to right <<  >> left to right < <= > >= left to right == != left to right & left to right ^ left to right | left to right && left to right || left to right ?: right to left = += -= *= /= %= &= ^= |= <<= >>= right to left , left to right Lowest