ICS 103: Computer Programming in C Handout-4 Topic: Arithmetic Expressions. Objective: • To know about basic data types of C. • To know about difference in / and % operators. • To know how to change type of variable at any place using type casting . • To Know rules for Evaluation of Arithmetic Expression. • To know how to use += , -=, *= , /= , %= compound assignment statements. • To know how to write mathematical formula in C. Data Types in C: Basic data types in C language are int, char, float and double. Data Type Bytes required for storing it in computer memory. Placeholder / Conversion specifier required with scanf or printf . int 2 %d char 1 %c float 4 %f double 8 %lf long int 4 %ld long double 10 %Lf Arithmetic Expressions: Use of / (Division Operator) and % (Mod Operator or Remainder Operator) : When an integer is divided by another integer the result is always an integer even if the answer consists of fractional value. For example 5 / 2 gives the answer as 2 though the actual answer is 2.5 because integer cannot have fraction. To avoid this inconsistency we use conversion operation called a cast . Placing the name of the desired data type in parentheses immediately before the value to be converted causes the value to be changed to the desired data format before it is used in computation . So, to get the correct answer for the previous case of 5 / 2 we write (double) 5 / (double) 2 or (float) 5 / (float) 2 . We can also write (double) 5 / 2 or (float) 5 / 2 because changing one operand will automatically change the other operand . This causes the value of the answer to Page 1 of 7
have fraction value and remember this casting doesnot change 5 and 2 to float or double, they will remain as integers only .
- Spring '10
- Algebra, Expression