C programming: Variables, Expressions part II
Data Types of Arithmetic ExpressionsRelational Expressions
Logical Expressions
Multiple AssignmentsCompound Assignment OperatorsIncrement/Decrement OperatorsOperator Precedence Table
Exercises
Data Type of an Arithmetic Expression
• Data type of an expression depends on the type of its operands – Data type conversion is done by the compiler
• If operators are *, /, +, or – , then the type of the result will be:– integer, if all operands are integer.– float, if all operands are integer and floats• If at least one operand is float and there is no double
– double, if at least one operand is double
Data Type of an Arithmetic Expression
Exampleint * int; int + float; double / float; int – double;int*int/float;float*int-int*double;int*(float+double);int/int;
result int
result float
result double
result double
result double
result double
result float
result int
Data Type of an Arithmetic Expression : (Continued)
• The data type of the target variable is also important
• If the result is a real number and the target variable is declared as integer, only the integer part of the result will be kept, and decimal part will be lost.
Example
The result is calculated as 16.66667But avg will be 16
on the left hand side of the assignment operator (‘=‘)
int avg;float sum=100.0, cnt = 6.0;avg = sum / cnt;
Data Type of an Arithmetic Expression : (Continued)
• Division operation is normally expected to give a real result but actually it may produce an integer result.
ExampleThe result of the division will be 16avg will be 16.0
float avg;int sum=100, cnt =
6;avg = sum / cnt; • Only the integer part of the result will be
considered if two operands are integer • Even when the target variable is float
Data Type of an Arithmetic Expression : (Continued)
#include <iostream.h>int main(){
int i=5, j=2, rm;float dv;j=j+1;rm= i%j;
dv= i/j;cout<<rm<<" "<<dv;
}
Example :
Data Type of an Arithmetic Expression : (Continued)Type Casting
#include <iostream.h>int main(){
int i=5, j=2, rm;float dv;j=j+1;rm= i%j;
dv= (float)i/j;cout<<rm<<" "<<dv;
}
Example :
Type cast: tells the compiler to treat i as a floating point number
Because of the type cast the result of the arithmetic operation is float and the target is also float.This means, we will see the correct result on the output.
Data Type of an Arithmetic Expression : (Continued)Type Casting
#include <iostream.h>int main(){
int i=5, j=2, rm;float dv;j=j+1;rm= i%j;
dv= i/(float)j;cout<<rm<<" "<<dv;
}
Example :
Type cast: tells the compiler to treat j as a floating point number
It does not matter whether the first or the second operand is float. If an arithmetic operation contains integer and floating point operands the result will be float.
Relational Expressions:• Relational expression is an expression which compares 2
operands and returns a TRUE or FALSE answer.Example : a >= b , a == c , a >= 99 , ‘A’ > ‘a’
• Relational expressions are used to test the conditions in selection, and looping statements.
== Equal To
!= Not Equal To
< Less Than
<= Less Than or Equal To
> Greater Than
>= Greater Than or Equal To
The operator that tests for equality is “= =”, not “=”.
“=” is the assignment operator.
Relational Expressions: (Continued)
int k=7;if ( k = 5) cout<<“ k is 5”;
Example
OutputA very common mistake is to use assignment (=)
operator instead of the relational
comparison operator (==)
This is an assignment statement. It actually assigns 5 to the variable k.Assignment statements are always evaluated to TRUE!!!!.
Relational Expressions: (Example)
• Write a program which will prompt the user to enter 2 integer numbers, ‘num1’, ‘num2’.
• The program would then compare these 2 numbers and display one of the following 3 options:
num1 > num2num1 < num2num1 = num2
START
NUM1 , NUM2
?NUM1 !=NUM2NUM1 = NUM2 ?
NUM1 > NUM2
NUM1 < NUM2
NUM1 > NUM2
STOP
YES YES
NO
NO
Relational Expressions: (Example)Flowchart
Relational Expressions: (Continued)#include <iostream.h>void main(){ int num1, num2; cout<<"Enter the Number 1 :"; cin>>num1; cout<<"Enter the Number 2 :"; cin>>num2; if (num1 != num2) { if (num1>num2) cout<<"Number 1 is greater then
Number 2"; else cout<<"Number 1 is smaller then
Number 2"; } else /* num1 is equal to num2*/ cout<<"\n Number1 is equal to Number 2";}
Logical Expressions• Logical Expressions are used to carry out logical
operations on – logical operands or – relational expression results.
• Logical Operators: Operator Meaning
! Not (Highest Priority)&& And|| Or (Lowest Priority)
. ______.
Logical Expressions: (Continued)
A B A || BF F F
T F T
F T T
T T T
OR ( || ) TABLE
Logical Expressions: (Continued)
A B A && BF F FT F FF T FT T T
AND ( && ) TABLE
Logical Expressions: (Continued)
A !AF TT F
NOT ( ! ) TABLE
Logical Expressions: (Example)
• Write an expression to check whether num1 is between 1 and 100 (inclusive)
if ( (num1 >= 1) && (num1 <=100) )…
• Here two conditions (num1 >= 1), and (num1 <=100) will be tested.
• Since the conditions are connected with && (And) logical operator, the overall result of the condition will be true only for the case when both of the conditions are true.– the action part of the “the overall result of the condition will be
true if” statement will be executed only when both conditions are satisfied
Logical Expressions: (Example)#include <iostream.h> /* Calculate the Letter Grade of a
student*/ void main() { int result; char grade; cout<<"\n Enter the exam result :";
cin>>result;if (result < 50)cout<<"\n Student got F";
if ((result < 60) && (result >= 50))cout<<"\n Student got D";if ((result < 70) && (result >= 60))cout<<"\n Student got C";if ((result < 80) && (result >= 70))cout<<"\n Student got B";if (result >= 80)cout<<"\n Student got A";
} /* End of main()*/
Multiple Assignment Statements• It is sometimes necessary to assign the same value to two or more
variables. This can be achieved in a single statement.• All targets must be variables• The value to be assigned must at the rightmost positionExample:
sum = 0;count = 0;
Can be written as sum = count = 0;
sum = 0=count = 0; 0=sum=count ; sum = 0=count; sum,count = 0;
The Compound Assignment Operators
Example
Operator Meaning
+ = is increased by
– = is decreased by
* = is multiplied by
/ = in divided by
k = k + 5; k += 5;
m = m - 100 ; m – = 100 ;
j = j * m ; j * = m ;
p = p \ r ; p / = r ;
Increment and Decrement Operators
Example
Operator Meaning
+ + Increment by one
– - Decrement by one
k = k + 1; k ++; or ++k;
k = k - 1; k ++; or ++k;
k = k++;
k = k--;
or
or
or
or
k = ++k;
k = --k;
Increment and Decrement Operators
• If the value produced by ++ or – – is not used in an expression, it does not matter whether it is a pre or a post increment (or decrement).
• When ++ (or – –) is used before the variable name, the
computer first increments (or decrements) the value of the variable and then uses its new value to evaluate the expression.
• When ++ (or – –) is used after the variable name, the computer uses the current value of the variable to evaluate the expression, and then it increments (or decrements) the value of the variable.
Increment and Decrement OperatorsExamplesFor each expression given below assume
a = 5; b = 7; c = 3;
d = ++b - a++; d = 8 – 5 = 3, b = 8, a=6After execution
d = a-- - --c; d = 6 – 2 = 4, a = 5, c=2After execution
d = a-- + c--; d = 5 + 2 = 7, a = 4, c=1After execution
d = --a + --c ; d = 3 + 0 = 3, a = 3, c=0After execution
d += ++d ; d = d + (d+1) = 3 + 4 = 7After execution
Operator PrecedenceOperators Associatively Type[ ] ( ) Left to right Highest++ -- ! Right to left Unary* / % Left to right Multiplicative+ - Left to right Additive< <= > >= Left to right Relational== != Left to right Equality&& Left to right Logical and|| Left to right Logical or?: Right to left Conditional= += -= *= /= %= Right to left Assignment
ExercisesWrite a program which will prompt the user to input the length and the with of a triangle. The program would then calculate and display the area.
#include <iostream.h>main(){ float height, base, area; cout<<“Enter the height = ”; cin>>height; cout<<“Enter the base = ”; cin>>base; area = 0.5*height *base; cout<<“The area is ”<<area;} /* End of Program*/
ExercisesWrite a program which will prompt the user to input the temperature in Fahrenheit. The program will then convert the Fahrenheit value to Centigrade using the following formula and display the result.
C = 9 / 5 ( f – 32 ).
# include <iostream.h>main(){ float c, f; cout<<“Enter the Fahrenheit temperature= ”; cin>>f; c = ( float ) 5/9 * (f – 32); cout<<“The Celsius temperature is ”<<c;}
ExercisesWrite a C program code which will prompt the user to input integer values to X and Y. It will then calculate and display X2+Y2 .
# include <iostream.h>main(){ int x, y, result; cout<<“Enter X :”; cin>>x;; cout<<“Enter Y :”; cin>>y; result = x*x + y*y; cout<<" x*x + y*y =”; cout<<result;}
# include <iostream.h>main(){ int x, y; cout<<“Enter X :”; cin>>x;; cout<<“Enter Y :”; cin>>y; result = x*x + y*y; cout<<" x*x + y*y =”; cout<< x*x + y*y;}
ExercisesWrite a C program code which will prompt the user to input 3 characters. The program would then display these characters from last to first.
# include <iostream.h>main(){ char ch1=‘ ’, ch2=‘ ’, ch3=‘ ’; cout<<“\n Enter a character string 3 characters long = ”; cin>>ch1>>ch2>>ch3; cout<<“The reverse of your string is ”; cout<<ch3<<‘ ’<<ch2<<‘ ’<<ch1;}
ExercisesWrite a C program code which will prompt the user to input a value for hours. The program would then transform and display this value of hours in minutes and seconds.
# include <iostream.h>main(){
int hours, min;long sec;cout<<“Hours = “;cin>>hours;min = hours * 60; sec =(long) min * 60;cout<<“ hours=“ << hours <<“minutes= “ << min << “seconds= “ << sec;
}
Exercises
Write a C program that reads in an integer value and then display it in float data type.
# include <iostream.h>main(){ int x; float y; cout<<“Enter an Integer = ”; cin>>x; y=x; cout<<“Now your value is a real number = “<< y;}
ExercisesWrite a C program that reads in radius (r) and height (h) of a cone and then calculates and displays the volume of the cone. (Hint: Vcone = 1/3*3.14*r2 * h)
# include <iostream.h>main(){ int r, h; float v; cout<<“\n Enter the radius = ”); cin>>r; cout<<“\n Enter the height = ”; cin>>h; v = 1 / 3* 3.14 * r * r * h; cout<<“\n The volume of the cone is ”<<v;}
ExercisesWrite a C program that reads two resistance values (R1 and R2) that are connected as parallel on a circuit, and it calculates the equivalent resistance of the circuit. [ Hint:Equivalent resistance Re = R1R2 / (R1 + R2) ]
# include <iostream.h>main(){ int r1, r2; float re; cout<<"\n Enter the resistance 1 = “; cin>>r1; cout<<"\n Enter the resistance 2 = “; cin>>r2; re = (float) r1 * r2 / (r1 + r2); cout<<"\n The equivalent Resistance is “<<re;}
ExercisesWrite a C program that reads in an integer (x) and then calculates and displays its square (x2) and its cube (x3).
# include <iostream.h>main(){ int x, x2, x3; cout<<n X = ”; cin>>x; x2 = x * x; x3 = x2 * x; cout<<“\n Square of X is ”<<x2<<“ cube of X is ”<<x3; }
THAT’S IT FOR NOW!