Introduction to Computing Programming is an activity that is carried out through some programming...

81
Introduction to Computing 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 desired output from the given input.

Transcript of Introduction to Computing Programming is an activity that is carried out through some programming...

Introduction to Computing

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.

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.

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.

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).

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.

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 doeshave 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.

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.

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.

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 ) + tp This 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.

Expressions, assignment

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

Sequencing is important: cont'dand

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.

Other kinds of instructions There are instructions which do something if some condition

holds.

For example, if ( x == y ) z = z + 1 The 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 - 1

This instruction increments z by 1 if x and y have same value, else it decrements z by 1.

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

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 form while( B ) S

where B is a boolean expression, and SS 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, otherwise SS is done again, and so on. SS gets done repeatedly till B becomes false.

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 - a

How 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.

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.

Example: cont'd

Observation time

Where in program

x y a b

1 Before 1st instn. 4 6 * *

2 Before 2nd instn 4 6 4 *

3 About to test a!=b 4 6 4 6

4 About to test a>b 4 6 4 6

5 About to test a!=b 4 6 4 2

6 About to test a > b 4 6 4 2

7 About to test a!=b 4 6 4 2

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.

Example: Cont’d

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.

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.

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.

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 approach

Step1 : Read listStep2 : Insert-Sort listStep3 : Print list

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; .

.

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 set a[i-1] as current element while (position not found) do if no more elements insert a[i] and report position found

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 */

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;

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]);}

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.

Names in CThese 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, ....

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.

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.

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

ConstantsLike 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.

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.

Constants: cont'd

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];

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.

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.

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.

Precedence of operators

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)

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.

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.

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.

Expressions: cont'd.

An assignment expression has the form: variable = expression

The 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.

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++;

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.

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 have expr1 = 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.

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.

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.

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.

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.

Type conversions: cont'd.

Across assignments:In an assignment expression the right-hand side is first

evaluated; the returned value is the value of the left-hand side and also the value of the assignment expression. The type of the left-hand side and that of the assignment expression is the type of the right hand side.

For example,if x is of type int and i is of char then as a result of the assignment x = i, x becomes of type char.

Type conversions: cont'd

Explicit type conversions This is done by using the cast operator. The syntax is :(type-name) expression

The meaning is that the type of the expression is changed to the type specified within round-brackets. For example,

sin((float) n)

converts the value of n to type float before passing it on to sin.

Input and Output

Basic Input Output Functions

• printf

• scanf

• getchar

• putchar

printf

It is a function in the standard library <stdio.h>It converts internal values to characters

The syntax is : printf( format string, arg1, arg2,...)

The format string contains, within double quotes, formatting information for the arguments to be printed viz., arg1, arg2,..

There is one group of characters for each argument.Each such group contains a percentage sign %,

followed by a conversion character

printf: cont'd.

For example, in the insertion sort program, we had

printf("%d\n", a[i]);

In this case, we had only one argument a[i], and its formatting information is given by %d, indicating that a[i] is a decimal integer. The \n indicates that after printing a[i] we should move to a newline.

printf: examples

#include <stdio.h>main()

{ char line[20] = “ramanujam"; int x = 123; float y = 123.45;printf("%d %f %s", x, y, line);}

Output:123 123.449997 ramanujam

printf: examples#include <stdio.h>

main() {

int i = 12345, j = -13579, k = -24680;long ix = 123456789;short sx = -2222;unsigned ux = 5555;float a = 2.2, b = -6.2;printf("%d %d %d %ld %d %u\n", i, j, k, ix, sx, ux);printf(" i = %3d j = %3d %3d \n", i, j, k);printf(" $%4.2f %7.1f% \n", a, b); }Output:

12345 -13579 -24680 123456789 -2222 5555 i = 12345 j = -13579 -24680

$2.20 -6.2%

We can summarise the formatting specifications as follows:

Each conversion specification begins with a % and ends with a conversion character. Between the % and the conversion character there may be, in order: A minus sign, which specifies left adjustment of the converted argument A number that specifies the minimum field width A period, which separates the field width from the precision A number that specifies the precision An h if the integer is to be printed as short or l if as long

printf: cont'd.

scanf This is a function in the standard library <stdio.h>.

It reads characters from standard input The syntax is: scanf( format string, arg1, arg2,...)

The format string contains, within double quotes, formatting information for the way the arguments are to be stored

It controls how arguments are storedThere is one group of characters for each argumentEach such group contains a percentage sign %,

followed by a conversion character

scanf: cont'd. Note that each argument is an address, indicating where

in the mory the corresponding argument is to be stored For example, in the insertion sort program we had

scanf("%d\n", &n);

the count of numbers to be read in.

In this case we had only one argument &n, and itsformatting information is given by %d, indicating that n is to be stored as a decimal integer. Once again the \n indicates that after reading n we should move to a newline.

scanf: examples

#include <stdio.h>

main() { char line[20]; int x ; float y ;

scanf("%d %f %s", &x, &y, line);}

scanf: examples cont'd The following data it can be entered during execution

12345 0.05 ramanujam

or even one per line as:

123450.05ramanujam

Note that we have a different conversion character for each of the three different argument types

scanf: examples cont'd. If we input the following data from the terminal 10 256.875 TAfter executing the following program

#include <stdio.h>main() {

char c; int i; float x; scanf("%3d %5f %c", &i, &x, &c);}

10 will be assigned to i, 256.8 to x and the character 7 to c.

Functions getchar and putchar

When we need to read or write data character by character, functions getchar and putchar are very handy.

To read a single character in variable c, we give:

c = getchar(); (equivalent to scanf("%c", &c);

To write the character in variable c, we give:putchar(c);

(equivalent to printf("%c", c);

The execution flow

The execution of any C program starts from the first line of the program and proceeds sequentially downwards.

For example, if a program has ten assignment statements, these would be executed in order of their appearance.

However, in most of the programs that we would like to write,we would want to execute some statements only if some condition holds.

For example, a program that takes as input marks between 0 and 100, and outputs FAIL if the marks are less than 40.

control statementWe use the if control statement to achieve this.

The syntax of an if statement is:

if ( condition) statement

The statement is executed only if the conditional expression condition is true, otherwise the control goes to the statement following the if statement.

Note that the statement may actually be a compoundstatement, or a control statement, or a combination.

Example program main()

{ int marks;

printf("input marks: "); scanf("%d", &marks);

if (marks < 40) /* fail */ printf("FAIL\n");}

The if-else statement

When, depending on a condition, we want to execute onestatement block or other, we use if-else statement.

Its syntax is: if ( condition)

statement1 else

statement2

statement1 is executed if the condition is satisfied otherwise statement2 is executed.

Example

main() { int marks; printf("input marks: "); scanf("%d", &marks); if ((marks < 0) || (marks > 100)) printf("Out of range!\n"); else if (marks < 40) /* fail */ printf("FAIL\n"); else /* pass */ printf("PASS\n"); }

Example

main(){ int a, b; printf("Give two numbers: "); scanf("%d %d", &a, &b); printf("\nLarger number is "); if (a > b) printf("%d\n", a); else printf("%d\n", b);}

if-else ladder

main(){

int marks; printf("input marks: ");

scanf("%d", &marks); if ((marks < 0) || (marks > 100)) printf("Out of range!\n"); else if (marks < 40) /* fail */ printf("Grade: F\n"); else if (marks < 70) printf("Grade: B\n"); else printf("Grade: A\n");}

The ?: operatorSuppose we want to assign different values to a

variable depending upon whether some condition is true or not.One way to do it is, of course, using an if-else statement.There is another, more concise, way of doing this via the ?: operator.The syntax of the operator is:

condition ? expn-1 : expn-2

The above expression returns the value of expression expn-1 if the conditional expression condition evaluates to true, otherwise returns the value of expn-2.

An exampleSuppose that there were only two rates of taxes:

No tax for income less than or equal to 150,000 and a flat rate of 10% above it.

Then the tax calculation program is:main(){ int income; float tax; printf("Enter the taxable income: "); scanf("%d", &income);

tax = (income <= 150000)? 0.0 : (income - 150000)*0.1;

printf ("tax= %f\n", tax);}

Correct but not advised example

main(){ int income; float tax; printf("Enter the taxable income: "); scanf("%d", &income); tax = (income <= 150000) ? 0.0 : ((income <= 300000) ? (income - 150000) * 0.10 : ((income <= 500000) ? 15000 + (income - 300000) * 0.2 : 55000 + (income - 500000) * 0.3))); printf ("tax= %f\n", tax);

}

Iterations: LoopsThe computational power of a machine is exploited

at the program level by means of constructs that repeat a set of actions again and again until some conditions are satisfied.

For example, in the Insertion-sort program we repeatedly take a new element from the unsorted list, and insert it into its proper place among the elements already seen and kept in sorted order.

Or consider evaluating the sine of a quantity x by using the power series expansion of sin x.

C has several repetitive constructs, like the for- loop, the while- loop etc.

The while - loop• Syntax:

while ( expression) statement

while is a key word, expression and statement are programmer-defined.

• Meaning of the construct:

The statement is executed as long as expression evaluates to true (non-zero value)

while loop: Example

. . while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; }

. . This while- loop had been used in the Insertion-sort program discussed earlier.

while - loop: example program #include <stdio.h>

#include <math.h>main(){

int sum, n; scanf("%d", &n); sum = 0; while (n != 0) sum += n % 10;

n /= 10; printf("The sum of the digits is = %d", sum)

}

The for - loopThe syntax:

for ( expr1; expr2; expr3) statement

Meaning of the construct:

The initialization of the loop-control variable is done by means of the expression expr1; the second expression expr2 controls the number of times the statement that follows is executed; the third expression expr3 updates the loop control variable after each execution of the statement.

for-loop: program first n positive numbers #include <stdio.h>

main()

{ int n, i; long sum; /*sum is a long integer*/ printf("How many numbers to sum ? ") ; scanf("%d", &n); /* input how many to*/ /*add */ sum = 0; for(i = 1; i <= n; i++) sum += i; printf("The sum is = %ld\n", sum);}

while versus for

A for- loop as a while- loop

expr1;while ( expr2) statement expr3;

Centralized loop control of for is an advantage in some situations.Otherwise the choice between the two is largely a matter of personal preference.