Download presentation

Presentation is loading. Please wait.

Published byMadison Alcock Modified about 1 year ago

1
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 2, Fundamental programming concepts (Simple programs) Tuesday 29 June 2010

2
OVERVIEW Revisit ‘Dumbo’ model for a program Structure of a C program Explanation of some nuances Sample program Notion of variables and data types Expression evaluation and assignment Problems needing non-sequential execution of instructions Conditional execution of instructions If statement and its variants

3
The Dumbo Model of computing We saw the abilities of a computer a model represented by Dumbo. A ‘program’ contains instructions executed sequentially. An instruction may Accept values as input, store these in designated memory locations A value may be computed by evaluating an expression, which is assigned to a location One or more values can be copied from memory locations and given to us as output

4
Computing … Memory Comprises of ‘locations’, each of which can contain a single value Each location has a tag or a name. Such name is called a ‘variable’ as the value in that location can change or vary based on operations A location is never empty, it always contains some value, may be from some previous computing activity

5
More about a program (student’s thoughts) When we discussed our sample programs (prog1.c and prog2.c), we noticed presence of several lines which we did not understand clearly. We will just identify these and take a note of the nuances we need to face as of now When we have done some more programming and have become more familiar with the computers, we will learn the full meaning of these lines We look at the problem of evaluating formula v = n1/n2 + x, for x=3, n1 = 2, and n2 = 5 (I expect v to be 3.4)

6
Program to evaluate a formula #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; }

7
Meaning of different lines #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } Does not make any sense, perhaps asking the computer to include some pre-written instructions

8
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } These appear to be comments meant for human readers

9
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } Seems to be something important but cannot understand the meaning. Perhaps the line indicates the beginning of our main program

10
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } Appears to define variables for the formula. I don’t understand the words int and float; int perhaps means integer, in which case, float should mean a real number

11
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } These are clearly the instructions written to solve the problem. However, the way the formula is written, the computer may first add n1 to x, and the result will be 1.0 which will be wrong

12
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } Looks like an output instruction similar to cout instruction. I am guessing this because of the word “print”, but why is it is written as ‘printf? Also, what do the funny symbols inside parenthesis mean?

13
Meaning of different lines … #include // prog3.c // arithmetic operations int main(){ int n1,n2; float x,v; n1 = 2; n2 = 5; x = 3; v = x + n1/n2; printf("value is %f\n", v); return 0; } This is very confusing! Perhaps the line indicates returning Value 0 to some one. But to whom? And why a zero?

14
In a nutshell When I execute the programs in the lab from files prog1.c, and prog2.c, these work correctly, collecting input values from me and returning the correct computed value as output So all those funny lines must have some purpose which I do not understand now However, I must understand the way my variables are defined, and the way computations are carried out, so that I can write instructions to correctly implement the desired calculations

15
Our Computing Environment The computer has evolved significantly. It can be instructed in a human like language, A tool called ‘compiler’ can translate these instructions in its machine language It can exchange with us, values in a form familiar to us (e.g. decimal numbers, fractions) and convert these to and from the internal binary representation A special program called ‘operating system’ controls its operations and its interaction with us

16
Our Computing Environment... We typically interact with a computer through a keyboard, using which we type our instructions, and data values and through a monitor, which displays to us, any value output by our program We interact with the operating system (OS), which is a set of prewritten programs to control the computers. This interaction is either through text interface where the OS shows us a ‘command prompt’, or using a graphical window interface, We use Ubuntu, a variant of Linux OS

17
A session with the computing environment [dbp@localhost ~]$ pwd /home/dbp [dbp@localhost ~]$ cd cpp [dbp@localhost ~]$ cc prog3.c [dbp@localhost cpp]$ ls prog1.c prog2.c prog3.c a.out [dbp@localhost cpp]$./a.out value is 3.000000

18
Handling Numerical values We define variable names used in our programs. Such definition allocates a memory location to the chosen name, and also defines the ‘type’ of value which can be stored in that location int N; : reserves one location in memory for N to store integer values. Max positive number: + 2 31 -1 Min negative number: - 2 31 -1 How to store larger numbers? We use Long integers: long M; Max magnitude 2 63 -1,

19
Handling Integer Numerical values … The computer actually uses ‘Binary’, or ‘Hexadecimal’ representation (Base 2 or 16) Thus value limits are expressed in powers of 2 or of 16 For the time being, we will continue to believe that computer uses Decimal values For integer values the base is immaterial Our Computer does arithmetic with constraints because of the limited capacity of a memory location What happens if two values are individually within the permissible range, but an arithmetic operation, such as multiplication, gives a larger result value?

20
Floating Point Representation Real numbers (fractions) are stored differently, using a “floating point” Two components of the number are stored in the same location in two separate compartments. One is called mantissa (m), and the other is called exponent (e) The Number value is taken as m * B e Computer uses B as 2 (Binary) or 16 We will take it to be our usual 10 In the program we write such values as 2.53, or -7.2E15 “float y;” reserves 1 location to store a number in this format.

21
Floating point … No decimal point is actually stored! It is assumed to be at the beginning of mantissa Can write as -.4127 E 11, or as -41.27 E 9 Mantissa can store about 7 decimal digits. Exponent can be between -100 and +100 double z; mantissa about 14 decimal digits -4127 +19462-21 11 -.4127 * 10 11.19462 * 10 -21

22
Problems in Numerical Computations Since computers offer limited precision, the computations carried out on given values often lead to inaccuracies, specially with floating point numbers Special care needs to be taken to handle such ‘round off’ errors There are many text books which show how these problems can be handled by using special techniques and algorithms in our programs Numerical recipes in C (C++, Java)

23
Example of problems with floating Point arithmetic float w, y=1.5, avogadro = 6.023 E 23 ; w = avogadro + y; What is the value of w? Exact value of w and avogadro will differ in the 23rd digit. “float” stores 7 digits of mantissa. Digits beyond are ignored. (roundoff error). So the value of w is same as avogadro (6.023 E 23)

24
Summary of our understanding so far “God made natural numbers, the rest is the work of man.” -- Leopold Kronecker “Humans made fractions and decimal numbers, the rest is the work of Dumbos” -- Deepak Phatak

25
Mixed Arithmetic computer converts from float to int and vice versa as needed. In a program, a number written without decimal point is taken as integer, otherwise as float int N=20; float y=15.8; N=y; : 15.8 is rounded down. N=15. 360/N : integer result is calculated. 360.0/N : float result is calculated.

26
Remarks on Arithmetic Arithmetic operators: *, /, %, +, -, *, / have higher precedence than +, - *, / have equal precedence, evaluated in left to right order. Similarly +, - x = m % n; % means modulo remainder for m=10, and n=4, x will have value 2. % same precedence as *, / () override default precedence.

27
Use of Comments Programs are read not only by compilers, but also by programmers and other humans You should include extra description (“comments”) to help other programmers figure out the logic: Style 1: “//......” to end of line Style 2: “/*.... */”

28
An important notion: Reassignment int m m =5; … m = 3*m + 1; // Reassignment This is not an equation, as it would be Mathematically absurd, because it would simplify to: 0 = 2*m+1 Computer interpretation: Calculate the value of the expression on rhs, then store it in the variable on lhs.

29
More on assignment... “increment” is a special form of reassignment count = count + 1; or count += 1; or, more simply, ++count; or count++; Input and Output instructions in C are not “natural” Handled through special “functions”

30
Conditional execution Program instructions are normally executed in the given sequence We can examine conditions, and based on the result, can execute instructions out of sequence if (condition) { statement group 1}; else { statement group 2};

31
Problem requiring conditional execution Based on the age of a passenger, the ticket cost for bus travel is different. Let us say, it is Rs 25.50 for an adult, and Rs 12.75 for a child (< 12 Years) Suppose we write our program as int age, float ticketcost; ticketcost = 12.75; ticketcost = 25.50; cout << ticketcost; We will always get cost as 25.50 If we exchange the two assignments, then we will always get 12.75

32
Use of if statement We need to execute either the first or the second instruction based on the value of age, but never both Use of the if – else statements will permit us to correctly evaluate the ticket cost... if (age > 12) {ticketcost = 25.50}; else {ticketcost = 12.75}; … What if elders are charged Rs 20?

33
If – else if ladder … if (age > 60){ ticketcost = 20.00;} else if (age > 12){ ticketcost = 25.50;} else { ticketcost = 12.75;} …

34
Example to find Maximum of given numbers // program 4 (prog4.cpp), find maximum of 3 given numbers #include using namespace std; int main() { int a, b, c, max; cout << “Give three numbers” << “\n”; cin >> a, b, c; max = a; if (b > max) {max = b}; if (c > max) {max = c}; cout <<“Maximum is”<< max<<"\n"; return 0; }

35
Finding Maximum … If there are more numbers, say 5, we could write: int a, b, c, d, e, max; cin >>a >>b >>c >>d >>e ; max = a; if (b > max) {max = b}; if (c > max) {max = c}; if (d > max) {max = d}; if (e > max) {max = e}; cout<<“Max is”<< max << "\n"; What do we write to find maximum of 200 numbers, or when number of numbers itself varies every time a user runs the program?

36
Specifying comparison Conditions “ a op b” where op is, =, ==, != == : is equal to != : is not equal to Conditions can be combined: (a > 0) && (a <= 9) : true if a is a positive digit. && : conjunction. “and” || : disjunction. “or” In the programming language C, evaluation of any condition results in a value 1 if the condition is true, and 0 if it is false

37
Questions?

38
Question From NIT Kurukshetra why do we use printf insted of print

39
Question From NIT Kurukshetra why do we use printf insted of print

40
Question From NIT Kurukshetra why do we use printf insted of print

41
Question From JEC_Kukas How will convert any floating point number in to integer number

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google