TMF1414 Introduction to Programming

Slides:



Advertisements
Similar presentations
Arithmetic Calculations
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
ICS 103 Lab 2-Arithmetic Expressions. Lab Objectives Learn different arithmetic operators Learn different arithmetic operators Learn how to use arithmetic.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
LESSON 6 – Arithmetic Operators
CMSC 1041 Functions II Functions that return a value.
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
C++ Programming Lecture 10 Functions – Part II
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Recap……Last Time [Variables, Data Types and Constants]
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Unary, Binary, logical Operations, Explicit type conversion Lecture 6 Instructor: Haya Sammaneh.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
1 Chapter 3 – Operators and Expressions Outline 3.1Introduction 3.2Arithmetic operators 3.3Relational operators 3.4Logical operators 3.5Assignment operators.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Variables, Operators, and Expressions
Simple C Programs.
Today Variable declaration Mathematical Operators Input and Output Lab
Arithmetic Expressions
CSE 220 – C Programming Expressions.
Functions Course conducted by: Md.Raihan ul Masood
Mathematical Functions
Chapter 7: Expressions and Assignment Statements
ARITHMETIC IN C Operators.
Chapter 4 C Program Control Part I
INSPIRING CREATIVE AND INNOVATIVE MINDS
BIL 104E Introduction to Scientific and Engineering Computing
© 2016 Pearson Education, Ltd. All rights reserved.
Functions, Part 2 of 2 Topics Functions That Return a Value
Relational Operations
Chapter 7: Expressions and Assignment Statements
Assignment and Arithmetic expressions
Arithmetic & other operations
CSC113: Computer Programming (Theory = 03, Lab = 01)
FUNCTIONS EXAMPLES.
Deitel- C:How to Program (5ed)
Fundamental of Java Programming Basics of Java Programming
Chapter 5 - Functions Outline 5.1 Introduction
Arithmetic Operator Operation Example + addition x + y
Chapter 5 - Functions Outline 5.1 Introduction
Structure of a C Program
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
Chapter 6 - Functions Outline 5.1 Introduction
A First Book of ANSI C Fourth Edition
C Operators, Operands, Expressions & Statements
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Introduction to Programming
Chapter 3 Operators and Expressions
Operator King Saud University
DATA TYPES There are four basic data types associated with variables:
Assignment Operators Topics Increment and Decrement Operators
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

TMF1414 Introduction to Programming Lecture 05 Arithmetic Calculation

Content Arithmetic Calculation Type of Arithmetic Expressions Basic Arithmetic Operators Increment and decrement Operators Compound assignment Operators Type of Arithmetic Expressions Explicit type conversions using cast operator Mathematical Library Functions Random Number Generation in C

Arithmetic Calculation Basic Arithmetic Operators 2 types of arithmetic Operators in C Unary Arithmetic Operators Binary Arithmetic Operators Require one operand Include unary plus(+), unary minus (-), increment (++), decrement (--) Unary plus (+) no effect on the result Unary minus (-) reverses the sign of the operand to which it applies (-ve value) Example: second += 100; // second = second + 100 second -=100; //second = second - 100

Arithmetic Calculation Binary Arithmetic Operators Require two operands Include +, -, *, / and % Can be integer or floating point numbers (except modulus-must be integer) Addition Subtraction Multiplication Division Remainder / Modulus + % * - / Symbol Operator Name Additive operator Multiplicative operator

VALUE BEFORE EXECUTION Arithmetic Calculation third = first + second; third = first - second; third = first * second; third = first / second; third = first % second; 1 5 3 2 4 No. Statement VALUE BEFORE EXECUTION first second third VALUE AFTER EXECUTION 100 7 ???

VALUE BEFORE EXECUTION Arithmetic Calculation Example Let int first = 100, second = 7, third; third = first + second; third = first - second; third = first * second; third = first / second; third = first % second; 1 5 3 2 4 No. Statement VALUE BEFORE EXECUTION first second third VALUE AFTER EXECUTION 100 7 ??? 107 93 14 700

Arithmetic Calculation C has two special operators for incrementing or decrementing a variable by 1: ++ (increment) --(decrement) Instead of writing count = count + 1; We can more concisely write count++; or ++count; Postfix form of the increment operator Prefix form of the increment operator

Arithmetic Calculation count = count – 1; count--; or --count; postdecrement predecrement Consider: Example 1 int count = 3; printf (“%d”, count++); // output: count = 3; printf (“%d”, count); // output: count = 4; Consider: Example 2 int count = 3; printf (“%d”, ++count); // output: count = 4; printf (“%d”, count); // output: count = 4;

Arithmetic Calculation Rules for Increment and Decrement Operators All increment and decrement operators are unary operators and they require variables as their operands. The postincrement operator has the side effect of incrementing its operand by one, after the expression in which it appears is evaluated using the operand’s previous value. Similarly, the postdecrement operator does not change the value of the operand while the expression is being evaluated. After the postdecrement operator is applied, the value of the operand is decremented by one. The preincrement and predecrement operators first generate their side effect; that is, they increment or decrement their operand by 1. Then, the expression in which they appear is evaluated. The precedence and associativity of the increment and decrement operators are the same as those of unary + and unary -..

Compound Assignment Operator Arithmetic Calculation Compound Assignment Operators To compute a value for an expression and store it in a variable, you have to use the assignment operator =. (known as simple assignment operator). C supports compound assignment operators, which are obtained by combining some operators with the simple assignment operator. Assign sum Assign difference Assign product Assign division Assign remainder += %= *= -= /= Symbol Compound Assignment Operator i.e. count += first count = count + first equivalence

Value of fourth after Execution Arithmetic Calculation Example: Assume int third = 13, fourth = 20; fourth += third; fourth -= third; fourth *= third; fourth /= third; fourth %= third; 1 5 3 2 4 No. Statement Value of fourth after Execution 6 8 10 7 9 fourth %= third + 4; fourth *= third + 4; fourth += third + 4; fourth /= third + 4; fourth -= third + 4;

Value of fourth after Execution Arithmetic Calculation Example: Assume int third = 13, fourth = 20; fourth += third; fourth -= third; fourth *= third; fourth /= third; fourth %= third; 1 5 3 2 4 No. Statement Value of fourth after Execution 33 7 260 6 8 10 9 fourth %= third + 4; fourth *= third + 4; fourth += third + 4; fourth /= third + 4; fourth -= third + 4; 11 264 37

Arithmetic Calculation Rules for Assigning a Type to Arithmetic Expressions that Involve int and double If one or more of the operands in an arithmetic expression are of type double, the result of the expression is also of type double. If all operands in an arithmetic expression are of type int, the result of the expression is also of type int. In an arithmetic assignment expression statement, the type of the entire statement and the type of the value stored in the variable to the left of the assignment operator are the same as the type of the variable itself.

Type of Arithmetic Expression Example Let double first = 4.7, second; int third = 27, fourth; 1. first = first + third; Step 1: computer converts the value of third to type double (27.0) in temporary storage and computes a floating-point value for the expression.  31.7 Step 2: computer assigns this value (31.7) to the variable first. Since both variable first and the computed expression are type double, no conversion is necessary in performing the assignment operation.

Type of Arithmetic Expression Explicit Type Conversions: The Cast Operator and Casting Once declared, the type of variable cannot be changed. However, sometimes, we may want to temporarily convert the types of the values of variables while computing expressions. Example #include<stdio.h> int main(void) { double amount, remnant; int no_of_fifties; printf(“Enter RM amount as a floating-point value:”); scanf(“%f”, &amount); no_of_fifties = amount / 50; remnant = ((amount * 100) % 5000) / 100.0; printf(“Number of fifties: %d\n”, no_of_fifties); printf(“Remnant: %f”, remnant); return 0; } // end function main

Type of Arithmetic Expression The warning appeared on first computation part where effecting of the assignment operation, there may be possible loss of value. Description: The reason is that the variable amount is of type double and, when divided by 50, will compute to a value that is also of type double. The variable no_of_fifties is of type int, and during the assignment operation, the value computed by the expression will be converted to an integer, thus resulting in the loss of the fractional part. The error occurs because of the subexpression (amount * 100) % 5000 in the expression to the right of the assignment operator. Description: In this expression one of the operands of the remainder operator % is of type double, since the variable amount is of type double. We know that the remainder operator requires integer operands.

Type of Arithmetic Expression Solution no_of_fifties = amount / 50; remnant = ((amount * 100) % 5000) / 100.0; Change to no_of_fifties = (int) amount / 50; remnant = ((int)(amount * 100) % 5000) / 100.0; Cast operator

Type of Arithmetic Expression Cast Operator It is a unary operator, and requires an expression as its operand. It converts the type of the operand in temporary storage to the type specified by the cast operator. The operand of the cast operator can be constant, variable, or expression. (if it is variable, the cast operator does not change the basic type of the variable itself; it change only the type of its value in temporary storage and uses this value in computing the expression in which it appears.) The operation of explicitly converting the type of an expression in temporary storage to a specified type is called casting. Form of a cast expression: (Type) Expression either int, double or char

Type of Arithmetic Expression Example Assume double first = 4.7; int second = 27; (int) (first + second); first = (int) first + second; first = (int) first % second; first = second % (int) first; 1 3 2 4 No. Statement 31 4.0 31.0 3.0 Value after Execution Output first 4.7

Mathematical Library Functions In C programming environments, there are two categories of mathematical functions: Those that accept as their arguments values of type double and return values of type double Those that accept and return only values of type int. Mathematical library functions are declared in standard header files. If you are planning to make use of them, you must have appropriate preprocessor directives in your program. The floating-point type function declarations are found in the math.h header file. #include <math.h> The integer type mathematical functions require the preprocessor directive #include <stdlib.h> To use the function, you have to use the proper function and know about the purpose, number and type of arguments and the type of values that are returned.

Mathematical Library Functions Returns the smallest integer larger than or equal to x. Returns the largest integer smaller than or equal to x. Returns the absolute value of x, where x is an integer. Returns the absolute value of x, where x is a floating-point value. Returns the square root of x, where x >= 0. ceil(x) sqrt(x) abs(x) floor(x) fabs(x) Function Purpose pow(x,y) sin(x) exp(x) log10(x) cos(x) tan(x) log(x) Returns the base-10 logarithm of x. Returns the exponential of x with the base e, where e is 2.718282. Returns the sine of x, where x is in radians. Returns x raised to the y power; if x is zero, y should be positive, and if x is negative, y should be an integer. Returns the natural logarithm of x. Returns the tangent of x, where x is radians. Returns the cosine of x, where x is in radians.

Mathematical Library Functions ceil(4.2) ceil(4.0) ceil(-5,7) sqrt(2.7) sqrt(2) abs(-12) abs(-12.7) floor(4.2) floor(4.0) floor(-5.7) fabs(-120) fabs(-120.8) Function Call Value Returned pow(2,3) pow(2.0, -3.2) pow(0,-3) pow(-2.0, 3.2) log(2) log10(2) exp(2.1) tan(45 * 3.141593/180) Example

Mathematical Library Functions 5.0 4.0 -5.0 -6.0 12.0 120.0 120.8 1.643168 ceil(4.2) ceil(4.0) ceil(-5.7) sqrt(2.7) sqrt(2) abs(-12) abs(-12.7) floor(4.2) floor(4.0) floor(-5.7) fabs(-120) fabs(-120.8) Function Call Value Returned pow(2,3) pow(2.0, -3.2) pow(0,-3) pow(-2.0, 3.2) log(2) log10(2) exp(2.1) tan(45 * 3.141593/180) 0.693147 0.30103 8.0 0.108819 Domain error 8.16617 1.0 Example

Random Number Generation rand function Load <stdlib.h> Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); Pseudorandom Preset sequence of "random" numbers Same sequence for every function call Scaling To get a random number between 1 and n 1 + ( rand() % n ) rand() % n returns a number between 0 and n - 1 Add 1 to make random number between 1 and n 1 + ( rand() % 6) number between 1 and 6

Random Number Generation (Cont.) For example, a program that simulates coin tossing might require only 0 for “heads” and 1 for “tails.” A dice-rolling program that simulates a six-sided die would require random integers from 1 to 6. Rolling a Six-Sided Die To demonstrate rand, let’s develop a program to simulate 20 rolls of a six-sided die and print the value of each roll. The function prototype for function rand is in <stdlib.h>. We use the remainder operator (%) in conjunction with rand as follows rand() % 6 to produce integers in the range 0 to 5.

©1992-2013 by Pearson Education, Inc. All Rights Reserved.

Random Number Generation (Cont.) Rolling a Six-Sided Die 6,000,000 Times To show that these numbers occur approximately with equal likelihood, let’s simulate 6,000,000 rolls of a die with the program of Fig. 5.12. Each integer from 1 to 6 should appear approximately 1,000,000 times. As the program output shows, by scaling and shifting we’ve used the rand function to realistically simulate the rolling of a six-sided die.

Random Number Generation (Cont.) Randomizing the Random Number Generator Executing the program of Fig. 5.11 again produces exactly the same sequence of values. How can these be random numbers? Ironically, this repeatability is an important characteristic of function rand.

Random Number Generation (Cont.) This is called randomizing and is accomplished with the standard library function srand. Function srand takes an unsigned integer argument and seeds function rand to produce a different sequence of random numbers for each execution of the program. We demonstrate function srand in Fig. 5.13.

Random Number Generation (Cont.) Function srand takes an unsigned int value as an argument. The conversion specifier %u is used to read an unsigned int value with scanf. The function prototype for srand is found in <stdlib.h>.

Random Number Generation srand function <stdlib.h> Takes an integer seed and jumps to that location in its "random" sequence srand( seed );

Random Number Generation

Random Number Generation Enter seed: 67 6 1 4 6 2 1 6 1 6 4 Enter seed: 867 2 4 6 1 6 1 1 3 6 2

Random Number Generation (Cont.) Let’s run the program several times and observe the results. Notice that a different sequence of random numbers is obtained each time the program is run, provided that a different seed is supplied. To randomize without entering a seed each time, use a statement like srand( time( NULL ) ); This causes the computer to read its clock to obtain the value for the seed automatically. The function prototype for time is in <time.h>.

Random Number Generation

Random Number Generation

What is the result of each of the following expressions? b) (1 + 2) * 4 / 2 c) 1 + 2 * (4 / 2) d) 9 % 2 + 1 e) (1 + (10 – (2 + 2)))

Convert each of the following formulas into its C assignment equivalents: a =

Show the value of x after each of the following statements is performed: x = fabs (7.5); x = floor (7.5); x = ceil (0.0); x = fabs (0.0);

What is the output? #include <stdio.h> c = a++; int main() { int a = 21; int b = 10; int c ; c = a + b; printf("Value of c is %d\n", c ); c = a - b; c = a * b; c = a / b; c = a % b; c = a++; printf("Value of c is %d\n", c ); c = a--; c = --a; printf("Value of c is %d\n", a ); }

What is the output ? #include<stdio.h> int main() { int a, b, c, d; int x = 10; a=x++; printf("value of a:%d\n", a); b=++x; printf("value of b:%d\n", b); c=--x; printf("value of c:%d\n", c); d=x--; printf("value of d:%d\n", d); printf("value of x:%d\n", x); return 0; }

Thank You