1 / 81

Introduction to Computing

melora
Télécharger la présentation

Introduction to Computing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming is an activity that is carried out through some programming language. Here the programming language we use is called C. Programming is instructing the computer how to solve a computational problem. In a computational problem, there will be some input , and for each input there is some desired output . A program instructs how to obtain the desiredoutput from the given input. Introduction to Computing

  2. Notion of a program A program is a sequence of instructions to the computer. For example, a program for adding two numbers may be that sequence of instructions which tells the computer how to carry out the algorithm for addition we had learnt in school. Given any two numbers to be added, the computer executes the program to find the result. Here the input is the two numbers, and the output is their sum.

  3. Other examples A more complex example of a computational problis the monthly pay-bill computation. Here, the input is various data about the ployees of a firm--- their attendance record, overtime record, salary, overtime rate etc. The output is the amount to be paid to each ployee. The program bodies the method of computing monthly salary.

  4. A program is a series of easy to follow steps: A computer knows how to carry out some simple instructions. Let us explain this idea by an example. Suppose we have a computer that knows how to carry out the instruction drawline (x1, y1, x2, y2) (x1, y1) and (x2, y2) are co-ordinates of any two points on the screen. This instruction makes the computer draw on the screen a straight line from point (x1, y1) to point (x2, y2).

  5. Complex tasks from simple tasks: The four instructions below drawline ( 0, 0, 0,10) drawline ( 0,10,10,10) drawline (10,10,10, 0) drawline (10, 0, 0, 0) when executed, will draw a square on the screen. Thus by performing a series of simple instructions, each drawing a straight line, we have managed to get a more complex task, drawing a square, done.

  6. Programming language C The programming language C provides a set of instructions. A program in C is a sequence of such instructions. C is complete: if a computational probl does have a solution, then it is possible to write a C program for the probl. Examples of other programming languages: Fortran, Basic, Cobol, Pascal, Prolog, Lisp, C++ etc. Moreover, it is easy to pick up many other languages once you know C.

  7. Basic Notions Now we introduce certain basic notions likethe notion of variables. We also discuss some basic kinds of instructions-- you will see their parallels in C shortly. Using these instructions, we shall write a programand discuss how the program works. This is not a C program but we hope it will prepare you for your first C program that you will see shortly.

  8. Variables A fundamental notion in languages like C is the notion of variables. A non-trivial program will have a number of variables.Each variable has a name, like x, tp, etc. as given by the programmer.At any time a variable has a value, and the value of the variable, in general, changes as the program executes.Recall that we said that a program is a sequence of instructions. It is these instructions which change, update, and/or test values of variables.

  9. Expressions, assignment Suppose a program has the variables x, y, z, and tp.Let us say that these variables have values 5, 3, -9, and 50.Consider 2 * ( x + y ) + tpThis is an expression, and it evaluates to a value, in this case, its value is 66. A fundamental instruction is assignment which assigns the value of an expression to a variable.The general form of assignment instruction is variable= expressionwhich tells the computer to first evaluate expression to get a value, and then assign this value to the variable.

  10. Sequencing of instructions is important Remember that executing a program is executing a sequence of instructions, which is what the program is. A program starts its execution by first executing the first instruction, then the second instruction, and so on. Execution of the program ends when there are no more instructions left to be executed. The order of sequencing of instructions is important. For example, the effect of two sequences. Sequence 1 y = x + y x = x + 1

  11. Sequencing is important: cont'd and Sequence 2 x = x + 1 y = x + y are different, even though both have the same two assignments.To see this, suppose we start with the case: x has 3, y has 5. Then effect of sequence 1 is:x has 4, y has 8.But the effect of sequence 2 will result in: x has 4, y has 9.

  12. Other kinds of instructions There are instructions which do something if some condition holds. For example,if ( x == y ) z = z + 1The effect of this instruction is to increment z by 1 only if x and y both have the same value, otherwise no value gets changed.An example of another form of such a conditional instruction is if ( x == y ) z = z + 1 else z = z - 1This instruction increments z by 1 if x and y have same value, else it decrements z by 1.

  13. Expressions evaluating to true/false In the above ( x == y ) is also an expression; its value is, however, not a number but true or false.Such expressions are called boolean expressions

  14. Iterative Instructions In a program, some action might need to be repeated till some condition is met. Iterative instructions help us in achieving this. One important instruction in this class has the formwhile( B ) S where B is a boolean expression, and S is a sequence of one or more instructions. On reaching such a statement, first B is tested, if false nothing gets done. But if B is true, S is done, and then B is tested again. If false, the work is over, otherwiseS is done again, and so on. S gets done repeatedly till B becomes false.

  15. Example Here is a `program', (not in C) using `instructions‘ that we have seen. a = x b = y while( a != b ) if( a > b ) a = a - b else b = b - aHow do we understand what this program is doing? We can see that there are four variables, x, y, a, and b, and the instructions modify a and b.To understand what the program does, we need to observe how the values of the variables change.

  16. When to observe To see changes, we would like to observe the values of variables just before and just after each instruction.But after an instruction, usually, another instruction follows.Therefore, we observe the variables just before an instruction is about to be executed.

  17. Example: cont'd

  18. Example: Cont’d When both a,b have the same value, (here it was 2), the test in while instruction evaluates to false. That ends the while instruction. After this, our example program had no other instructions to execute, therefore, the execution of the program ends.What we have done is to hand-execute the program. The final value of a in this case is 2.Had we started with x as 12 and y as 8, the final value of a would have been 4.In general, the final value of a will be the gcd of x and y, provided both are greater than 0.Therefore, the program is doing something useful! To compute gcd of x and y, we can execute the program, and print the final value of a as the result.

  19. Programming Language C • Now, we shall discuss a problem which is to be solved using the computers. • We shall design a method to solve the problem, and then implement the method using a C program.

  20. A problem Arrange a list of n numbers a1, a2, a3, ..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion sort works as follows: we look at the numbers one by one, maintaining the numbers already seen in sorted order. Each new number is inserted into its proper place in this sorted list so that the sorted order is preserved.

  21. A solution: cont'd. Suppose the given list of numbers is 5, 7, -3, 2, 20. Following the idea above, we obtain the following sorted lists increntally:5 ( after inserting 5 into its proper place in an pty list !) 5, 7 (after inserting 7 ...)-3, 5, 7 (after inserting -3 ...)-3, 2, 5, 7 (after inserting 2...)-3, 2, 5, 7, 20 (after inserting 20....)Finally, we obtain a sorted list of all the numbers.

  22. A program for insertion sort We address the problem of designing a program for insertion sort. The approach that we shall adopt is one of handling complexity by adding details incrementally. This is popularly known as the top-down or stepwise refinement approach to programming. A first cut in a top-down approachStep1 :Read listStep2 : Insert-Sort listStep3 : Print list

  23. A program for insertion sort: cont'd. • Top-down approach : A second cut . . Step 2 : for i = 1 to n do insert a[i] into sorted(a[1], a[2], ..., a[i-1]), by linear search from the high-end;. .

  24. A program for insertion sort: cont'd. Top-down approach: A third cut To insert a[i]| we first claim space for it to the right of a[i-1]| and propagate it left if necessary. Step 2:for i = 2 to n do seta[i-1] as current elementwhile (position not found) do if no more elements inserta[i] and report position found

  25. Full-fledged C-program #include <stdio.h>main(){ int n; /* number of elements to sort */ int i, j; /* loop counters */ int key; /* element to insert */ int a[15]; /* storage for list */ /* read in the list */

  26. Full-fledged C program: cont'd. scanf("%dn", &n); /*n is the number of integers to be sorted */ for (i=0; i<n; i++) scanf("%d", &a[i]); /*read in the numbers *//* find the correct position of key, that is a[j], */ /*in the sorted list a[0],a[1], ... ,a[j-1] */ for (j=1; j<n; j++) /* initialize while-loop variables */ key = a[j]; i=j-1;

  27. Full-fledged C program: cont'd. while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; } /* insert key in the correct position */ a[i+1] = key;/* print the sorted list */ for (i=0; i<n; i++) printf("%d\n", a[i]);}

  28. Variables and constants Data that can be changed by the actions in a program are called variables. Variables have names and locations in mory corresponding to these names, that store the associated values. Data that cannot be changed by the actions in a program are called constants. There may or may not be (symbolic) names corresponding to constants.

  29. Names in C These are a combination of letters, digits and underscore, beginning with a letter. • At most 31 characters long • Case-sensitive • Variable names in lower case • Names of symbolic constants in upper case • Keywords like else, if... cannot be used Examples of valid names: abc, a_bc, a12, a_1_b, ABc, A_Bc, PI, .... Some invalid ones are: a-bc, 1ab, A b, ....

  30. Basic types in C The type of a variable indicates the values that it can assume Among other things, we need different types of variables to be able to handle different types of data In C, we have variables of the following basic types: • char : The type char corresponds to the set of all possible 8-bit (that is a byte) values. • int : The type int denotes the set of values that can be stored in a number of bits equal to the host machine's word size.

  31. Basic types in C: cont'd. • float: The type float corresponds to the set of floating-point numbers that can be represented in the host machine. • double: The type double corresponds to the set of double-precision floating-point numbers that can be represented in the host machine.

  32. Qualified types We get more types by qualifying the basic types: signed, unsigned, long, short int give us eight different ways of prefixing the type int. For example, signed long int, short int etc. signed, unsigned char give us two different ways of prefixing the type char. For example, signed char long double We can prefix the type double by long

  33. Constants Like variables, we also have different types of constants. Numerical constants are of the types: • integers: For example, 123, -12354 etc. • integers suffixed with u, U l, L 123457L or 1234567l is of type long int; 1234567uL is of type unsigned long • integers in octal and hex representation • An octal integer constant is prefixed with 0; • a hexadecimal integer constant with 0x or 0X; 077 is the octal equivalent of 63, while 0xAF is the hexadecimal equivalent of 175. These can also be suffixed with u, U and l, L. For example, 077777U is an unsigned octal constant.

  34. Constants: cont'd String constants: These are a sequence of 0 or more characters put inside double quotes. For example, "I am going“. Enumeration constants: We can define our own type, by associating a name with this type and explicitly enumerating the associated set. A constant of the enumerated type is one of a list of values of such an explicitly enumerated type. For example, enum hotmonths {MAY, JUNE, JULY, AUGUST} is an enumerated type. MAY, JUNE, JULY, AUGUST are enumerated (symbolic) constants in this list whose values are 0, 1, 2, 3 respectively.

  35. Declarations What are declarations? A C program is made up of declarations, followed by statements. In the declarations part we describe the data, that is, choose suitable names and types for the data. For example : int lower, upper, step; char c, line[100];

  36. Declarations: Cont’d Why declarations ? The most important reason is that declarations enable a compiler to check that the actions that are being performed on this data are indeed permissible. The technical term for this is type-checking. It also enables a programmer to control the life-time (or scope) of any data.

  37. Operators, Expressions, and Statements Operators allow us to manipulate the data represented by constants and variables Arithmetic operators: +, *, /, -, %. The first four are the familiar plus, product, division, subtraction; while the last is themodulus operator - a % b gives the remainder in the division of a by b.

  38. Precedence of operators Operators are used with variables and constants to build up expressions. For example, a + b - 2 is an expression. In the presence of several operators in any expression, the rules that tell us the order in which to do the operations are called precedence rules. The precedence of binary +, - are the same; so are those of *, /, %; the unary + and - also have the same precedence. The first group has lower precedence than the second which in turn have lower precedence than the third. In cases of equal precedence, arithmetic operators associate from left to right. With these rules, the expression 2 * 3 - 4evaluates to 2 instead of -2.

  39. Relational & Equality Operators Relational : <, <=, > Equality : ==, != Equality operators have higher precedence than relational but lower than arithmetic operators. Evaluation of the expression 2 < 3 != 5 gives us 0 (which is the value of false in C)

  40. Logical operators The relational operators give us relational expressions which are combined using the logical operators: and (&&), or (||), not (!) For example, in the expression i >= 0 && a[i] > keyprecedence order is >=, >, && The precedence of || is lower than that of &&; while both have lower precedence than the equality operators. The unary operator ! converts a non-zero operand true into false ( 0), and a 0 operand into 1.

  41. Operators: cont'd Increment operator ++: it is a unary operator which can be prefixed or suffixed to its operand. The effect is to increase the value of itsoperand by 1. Thus the effect of both ++n and n++is to increase n by 1. Decrement operator - -: it is a unary operator which can be prefixed or suffixed to its operand. The effect is to decrease the value of itsoperand by 1. Thus the effect of both --n and n-- is to decrease n by 1.

  42. Expressions An expression is made up of variables, constants and operators. An arithmetic expression evaluates to a numerical value. A boolean expression is either a relational expression or a logical expression that evaluates to true or false. For example, if a, b, c are all of type int then a + b - c is an arithmetic expression, a != b is a relational one and (a < b) && (b > c) is a logical expression.

  43. Expressions: cont'd. An assignment expression has the form: variable = expressionThe value of such an expression is the value of its left-operand, obtained by evaluating the expression on the right. Thus as a result of the assignment x = 5 + 2; x has the value 7.

  44. statements A statement causes an action to be carried out. In C, statements are either expression statements,compound statements or control statements. Expression statement: This is an expression, terminated by a semicolon. For example:a = 3; c = a + b; n++;

  45. statements: cont'd. Compound statements: These consist of several statements enclosed with a pair of braces For example:while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; } Control statements: We will discuss these later.

  46. Operators Once More Assignment operator: This has the form op=. The assignment expression n = n + 2 can be written as n += 2.As such n and 2 become the operands of the operator +=.In general, if op is a binary operator, we haveexpr1 = expr1 op expr2,which can be written as expr1 op= expr2so that expr1 and expr2 are the operands of the operator op= which we call the assignment operator.

  47. The sizeof operator The sizeof operator operates on either a variable name, or a type name. It gives the number of bytes occupied by the givenvariable, or any variable of the given type respectively. For example:sizeof(int)would have the value 4.

  48. Precedence among operators Operators Associativity ( ) [ ] left to right ! ++ -- + - * type sizeof right to left * / % left to right + - left to right < <= > >= left to right == != left to right && left to right || left to right ? : right to left = += -= *= /= %= left to right The precedence decreases from the top to thebottom of the table.

  49. Type conversions The constituent variables and constants in an expression can be of different types. Then the question that naturally arises is what is the type of the value of an expression. For example, if in the expression a + b, a is of type int and b is of type float, then what is the type of the sum? Type conversion rules tell us what should be the type of the sum. We address these questions in the next couple of slides.

  50. Type conversions: cont'd. Implicit type conversionsSuch conversions in C take place in several contexts. In arithmetic operations: When operands of an arithmetic operator have different types.For example, if a is of type int and b is of type char then the type of the result of a + b is int. The general rule here is that 'a lower' type is elevated to 'a higher' type.

More Related