Showing posts with label Arithmetic Operators. Show all posts
Showing posts with label Arithmetic Operators. Show all posts

Conditional Statements

Tuesday, June 12, 2012
In every day life, we are often making decisions. We perform different tasks while taking decisions. For example, the statement ‘Bring one litre of milk while returning home from college, if the milk shop is open’ involves this phenomenon.
In this statement, there is an element of decision making. We bring one litre of milk if the shop is open. And if the shop is closed, we come back to home without milk.
Thus we are making a decision on the condition that the shop is open. The decision-making process is everywhere in our daily life. We see that the college gives admission to a student if he has the required percentage in his previous examination and/or in the entry test. Similarly administration of a basketball team of the college decides that the students having height more than six feet can be members of the team.
For writing interesting and useful programs, we have to develop the decision making power in them.
Now we will see what kind of decisions are in programming and how these can be used.

Every programming language provides a structure for decision making.
'C' also provides this structure. The statement used for decisions in 'C' language is known as the 'if statement'. The if statement has a simple structure. That is



We explain it as if condition is true, then execute the statement or a group of statements. Here the condition is a statement which explains the condition on which a decision will be made. We can understand it from the example that Ali can become the member of the basket ball team if he has a height more than six feet .In this case, the condition will be



We have written the condition in English language. Now let's see how we can implement this in terms of variables, operators and C statements. In the program, we will write the condition in parentheses, followed by a statement or group of statements to be executed.
Now here is the concept of block of statements. We use braces { } to make a group (block) of a number of statements. We put ‘{’ before first statement and ‘}’ after the last statement. Thus if we have to do many things after the if statement. The structure of if statement becomes as under



Note the indentation of the lines and semi-colon after each statement. Semi-colons are necessary after every C statement. The indentation is only a matter of style. It makes the code easy to read and understand from where a block starts, ends and what kind of block it is. It does not affect the logic of the program. But the braces can affect the logic. We can also write a comment line to state the purpose of code block.
Let's consider a simple example to explain the if statement. Suppose, we have ages of two students (say for the time being we have got these ages in variables). These variables are- age1 and age2. Now we say that if the age1 is greater than age2, then display the statement ‘Student 1 is older than student 2’.
The coding for this program will be as below



Here, in our code we see a new operator i.e. ‘ > ‘ (greater than) in the if statement. We need such operators (like greater than, less than, equal to etc) while making decisions. These operators are called 'relational operators'. These are almost the same relational operators we use in algebra.
Following table summarizes the relational operators.








AlgebraicIn C languageExampleMeaning
Greater than > > x > yx is greater than y
Equal to = == x == yX is equal to y
Less than < < x < yX is less than y
Greater than or equal to>=x >= yx is greater than or equal to y
Less than or equal to<=x <= yx is less than or equal to y
Not equal to!=x != yx is not equal to y

Note that there is no space between ==, >=, <= and !=. These are considered as single operators. The operator == (equal to) is different from the operator =. We know that operator = is the assignment operator which is used in assignment statement to assign a value to a variable. Don't confuse the assignment operator (=) with equal to operator (==). If we write single = in condition of if statement. For example, if we write if ( x = 2 ), the compiler will not give error. This means that it is not a syntax error. The conditional expression in if statement returns a value. In this case, x = 2 will also have some value but it will not in the form of true or false. So it will create a logical error. So be careful while using equal to condition in if statement. For previous lesson click here: Use of Operators
For next lesson click here: Flow Charting


the easiest way to learn programming
introduction to programming
Conditional Statements

Examples of Expressions

Tuesday, May 29, 2012
We have already seen the precedence of arithmetic operators. We have expressions for different calculations in algebraic form, and in our programs we write them in the form of C statements. Let’s discuss some more examples to get a better understanding.

We know about the quadratic equation in algebra, that is y = ax2 + bx + c. The quadratic equation in C will be written as y = a * x * x + b * x + c. In C, it is not an equation but an assignment statement. We can use parentheses in this statement, this will make the expression statement easy to read and understand. Thus we can rewrite it as y = a * (x * x) + (b * y) + c.

Note that we have no power operator in C, just use * to multiply the same value.

Here is another expression in algebra: x = ax + by + cz2. In C the above expression will be as:

x = a * x + b * y + c * z * z

The * operator will be evaluated before the + operator. We can rewrite the above statement with the use of parentheses. The same expressions can be written as:

x = (a * x) + (b * y) + c * ( z * z)

Lets have an other expression in algebra as x = a(x + b(y + cz2)). The parentheses in this equation forces the order of evaluation. This expression will be written in C as:

x = a * (x + b * (y + c * z * z))

While writing expressions in C we should keep in mind the precedence of the operators and the order of evaluation of the expressions (expressions are evaluated from left to right). Parentheses are used in complicated expressions. In algebra, there may be curly brackets { } and square brackets [ ] in an expression but in C we have only parentheses ( ). Using parentheses, we can make a complex expression easy to read and understand and can force the order of evaluation. We have to be very careful while using parentheses, as parentheses at wrong place can cause an incorrect result. For example a statement x = 2 + 4 * 3 results x = 14. As * operator is of higher precedence, 4 * 3 is evaluated first and then result 12 is added to 4 which gives the result 14. We can rewrite this statement, with the use of parentheses to show it clearly, that multiplication is performed first. Thus we can write it as x = 2 + (4 * 3). But the same statement with different parentheses like x = (2 + 4) * 3 will give the result 18, so we have to be careful while using parenthesis and the evaluation order of the expression.

Similarly the equation (b^2 – 4ac)/2a can be written as ( b * b – 4 * a * c) / ( 2 * a ). The same statement without using parentheses will be as b * b – 4 * a * c / 2 * a. This is wrong as it evaluates to b^2 – 4ac/2a (i.e. 4ac is divided by 2a instead of (b^2-4ac)).

For previous lesson click here: Sample Program
For next lesson click here: Use of Operators


the easiest way to learn programming
introduction to programming
Examples of Expressions

Precedence of Operators

Monday, May 28, 2012
The arithmetic operators in an expression are evaluated according to their precedence. The precedence means which operator will be evaluated first and which will be evaluated after that and so on. In an expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses( ) are evaluated first. If there are nested parentheses then the inner most is evaluated first.

The expressions are always evaluated from left to right. The operators *, / and % have the highest precedence after parentheses. These operators are evaluated before + and – operators. Thus + and – operators has the lowest precedence. It means that if there are * and + operators in an expression then first the * will be evaluated and then its result will be added to other operand. If there are * and / operators in an expression (both have the same precedence) then the operator which occurs first from left will be evaluated first and then the next, except you force any operator to evaluate by putting parentheses around it.

The following table explains the precedence of the arithmetic operators:

Operators Operations Precedence (Order of evaluation)
( ) Parentheses Evaluated first
*, /, or % Multiplication, Division, Modulus Evaluated second. If there are several, they are evaluated from left to right
+ or - Addition, Subtraction Evaluated last. If there are several, they are evaluated from left to right

Lets look some examples.

What is the result of 10 + 10 * 5 ?

The answer is 60 not 100. As * has higher precedence than + so 10 * 5 is evaluated first and then the answer 50 is added to 10 and we get the result 60. The answer will be 100 if we force the addition operation to be done first by putting 10 + 10 in parentheses. Thus the same expression rewritten as (10 + 10) * 5 will give the result 100. Note that how the parentheses affect the evaluation of an expression.

Similarly the expression 5 * 3 + 6 / 3 gives the answer 17, and not 7. The evaluation of this expression can be clarified by writing it with the use of parentheses as (5 * 3) + (6 / 3) which gives 15 + 2 = 17. Thus you should be careful while writing arithmetic expressions.

Tips
  • Use spaces in the coding to make it easy to read and understand
  • Reserved words can not be used as variable names
  • There is always a main( ) in a C program that is the starting point of execution
  • Write one statement per line
  • Type parentheses ’( )’ and braces ‘{ }’ in pairs
  • Use parentheses for clarification in arithmetic expressions
  • Don’t forget semicolon at the end of each statement
  • C Language is case sensitive so variable names x and X are two different variables

For previous lesson click here: Arithmetic Operators
For next lesson click here: Sample Program


the easiest way to learn programming
introduction to programming
Precedence of Operators

Arithmetic Operators

In C language we have the usual arithmetic operators for addition, subtraction, multiplication and division. C also provides a special arithmetic operator which is called modulus. All these operators are binary operators which means they operate on two operands. So we need two values for addition, subtraction, multiplication, division and modulus.

Arithmetic OperationArithmetic OperatorAlgebraic ExpressionC Expression
Addition+x + yx + y
Subtraction-x - yx - y
Multiplication*xyx * y
Division/x ÷ y, x / yx / y
Modulus%x mod yx % y

Addition, subtraction and multiplication are same as we use in algebra.
There is one thing to note in division that when we use integer division (i.e. both operands are integers) yields an integer result. This means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after decimal) is ignored. If we want to get the correct result, then we should use float data type.

The modulus operator returns the remainder after division. This operator can only be used with integer operands. The expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will be 1, 23 % 5 will be 3 and 107 % 10 will be 7.

Sample Program 2
This is a sample program that uses the arithmetic operators. It displays the result of arithmetic operations on the screen. To make the result more visible we have used end line character (endl) with cout. So the statement:

cout << endl;

Simply ends the current line on the screen and the next cout statement displayed at the next line on the screen.

Code of The Program(Operation with integers)

Output of the program

Code of The Program(Operation with decimal numbers)

Output of the program

see everything clearly
// A Sample Program that uses Arithmetic Operators.

#include

main ()
{
//declaration of variables
int a;
int b;
int c;

float x;
float y;
float z;

// assigning values to variables
a = 23;
b = 5;
x = 12.5;
y = 2.25;

// processing and display with integer values
cout << "Operations with integers" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; //addition c = a + b; cout << "a + b = " << c << endl; //subtraction c = a - b; cout << "a - b = " << c << endl; //multiplication c = a * b; cout << "a * b = " << c << endl; // division c = a / b; cout << "a / b = " << c << endl; //modulus c = a % b; cout << "a % b = " << c << endl; // processing and display with decimal values cout << "Operations with decimal numbers" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; //addition z = x + y; cout << "x + y = " << z << endl; //subtraction z = x - y; cout << "x - y = " << z << endl; //multiplication z = x * y; cout << "x * y = " << z << endl; //division z = x / y; cout << "x / y = " << z << endl; } Output of the program
Operations with integers

a = 23
b = 5
a + b = 28
a - b = 18
a * b = 115
a / b = 4
a % b = 3

Operations with decimal numbers

x = 12.5
y = 2.25
x + y = 14.75
x - y = 10.25
x * y = 28.125
x / y = 5.55556

For previous lesson click here: Data Types
For next lesson click here: Precedence of Operators


the easiest way to learn programming
introduction to programming
Arithmetic Operators

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger