Cs1100lec05 07
Cs1100lec05 07
Repetitive Statements
A very important type of statement iterating or repeating a set of operations - a very common requirement in algorithms C offers three iterative constructs
Programming problems
Write a program to check if a given number is prime. (can this be done without using a logical decision?) Write a program to count the number of digits in a given number. Your answer should contain two parts, number of digits before and after the decimal. (can you do this only with assignments to variables, and decisions?)
{
value = 2 * value; printf(current value is %d \n, value);
counter = counter + 1;
} }
More on Loops
Two kinds sentinel-controlled and counter controlled. Counter loop runs till counter reaches its limit. Use it when the number of repetitions is known. Sentinel loop runs till a certain condition is encountered. Example a \n (newline) is encountered in the input. Use it when the number of repetitions is a property of the input and not of the problem being solved.
PSK, NSN, DK, TAG CS&E, IIT M 8
For loops
Counter controlled repetitions needs - Initial value, - modification of counter: +i, -i, any other arithmetic based modification which is based on the problem, and - Final value. For repetition structure provides for the programmer to specify all these. Everything that is provided by for can be achieved using while. Use of for helps make the program error free
PSK, NSN, DK, TAG CS&E, IIT M 9
Example
Replace our previous program by the following for (count = 0; count <=n; count=count+1) { if (count == 0) printf(value is %d \n,1); else { value = 2 * value; printf(value is %d \n, value); } } Observe: a mistake in the earlier program is gone.
PSK, NSN, DK, TAG CS&E, IIT M 11
CS110 Lecture 6
Shankar Balachandran [email protected] Sukhendhu Das [email protected]
12
Expected Output :
year Amount in the deposit 1050.00 1102.50 1157.62 1215.51 1276.28 1340.10 1407.10 1477.46 1551.33 1628.89
15
1 2 3 4
5 6 7 8 9 10
An Example
x is the given number
y is the number being computed
y=0
y = 0*10 + 2 = 2 y = 2*10 + 4 = 24 y = 24*10 + 3 = 243 y = 243*10 + 6 = 2436 y = 2436*10 + 5 = 24365
x = 56342
x = 5634 x = 563 x = 56 x=5 x=0
Termination condition: Stop when x becomes zero 17
Reversing a number
main( ){ int x = 0; int y = 0; printf("input an integer :\n"); scanf("%d", &x); while(x > 0){ y = 10*y + ( x % 10 ); Remember integer division x = (x / 10); truncates the quotient } printf("The reversed number is %d \n", y); }
Exercise: Try this program for n=120, n=1400. Fix problems if there are any.
PSK, NSN, DK, TAG CS&E, IIT M 18
main ( ) { int d, n, sum; scanf(%d, &n); for (sum = 1, d = 2; d <= (n/2); d++) { if (n%d == 0) sum += d; }
if (sum == n) printf (%d is perfect\n, n); else printf(%d is not perfect\n, n);
}
PSK, NSN, DK, TAG CS&E, IIT M
CS110 Lecture 7
Shankar Balachandran [email protected] Sukhendhu Das [email protected]
21
22
23
NewtonRaphson method
f ' denotes the derivative of the function f. By simple algebra we can derive:
http://en.wikipedia.org/wiki/Newton's_method
PSK, NSN, DK, TAG CS&E, IIT M 24
Repetition Structures
expr
body body
f
While Structure
init
expr
t
Do/While Structure
expr
body
incr
For Structure
25
Structured Programming
To produce program that are
easier to develop, understand, test, modify easier to get correctness proof
Rules
1 Begin with the simplest flowchart. 2 Any action box can be replaced by two action boxes in sequence. 3 Any action box can be replaced by any elementary structures (sequence, if, if/else, switch, while, do/while or for ). 4 Rules 2 and 3 can be applied as many times as required and in any order.
PSK, NSN, DK, TAG CS&E, IIT M 26
Spaghetti programming
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. First line IF (condition1) Goto 13 Third line If (condition 2) go to 7 Fourth line Fifth line Go to 3 Sixth line If (condition 3) go to 12 Go to 8 Line number 11 Line 12 If (condition 4) go to 1 Print (Im done finally !) End
27
Exercises
Write a program that reads in the entries of a 3 by 3 matrix, and prints it out in the form of a matrix. The entries could be floating point too. Write a program that reads in orders of two matrices and decides whether two such matrices can be multiplied. Print out the decision. Write a program that reads in two matrices, and multiplies them. Your output should be the two matrices and the resulting product matrix.
PSK, NSN, DK, TAG CS&E, IIT M 28
30
Counting digits
case : case\n: case\t: nWhite++; break; default: nOther++; break; } } printf(Digits: \n) for(i=0;i<10;i++) printf(\t%d occurred %d times \n, i, nDigit[i]); printf(White spaces: %d, other: %d\n, nWhite, nOther);
PSK, NSN, DK, TAG CS&E, IIT M
31
32
An Array
A data structure containing items of same data type Declaration: array name, storage reservation
int marks[7] = {22,15,75,56,10,33,45}; - a contiguous group of memory locations named marks for holding 7 integer items - elements/components - variables
marks[0], marks[1], , marks[6] marks[i] i - position / subscript (0 i 6) 22 15 75 56 0 1 2 3
10
33
4
5 6
33
45
Polynomial Evaluation
Evaluate p(x) = anxn + an-1xn-1 + an-2xn-2 + a1x + a0 at a given x value. Computing each term and summing up
n + (n-1) + (n-2) + + 1 + 0 = n(n+1)/2 multiplications and n additions
Improved Method:
p(x) = a0 + x(a1 + x(a2 + x(a3 + + x(an-1 + xan)))) for instance, p(x) = 10x3 + 4x2 + 5x + 2 = 2 + x(5 + x(4 + 10x)) n multiplications and n additions will run faster!
PSK, NSN, DK, TAG CS&E, IIT M 35
Polynomial Evaluation
#include <stdio.h> main(){ int coeff[20], n, x, value, i; /*max. no. of coeff s is 20*/ scanf(%d%d, &n, &x); /*read degree and evaluation point*/ for(i = 0; i <= n; i++) scanf(%d, &coeff[i]); /* read in the coefficients */ value = coeff[n]; for(i = (n-1); i >= 0; i--) value = x*value + coeff[i]; } /* a0 */ /* evaluate p(x) */
36
More Exercises
1. Sort an array of numbers into ascending order.
a) Write the output into another array Assuming that arrays are expensive, use only one array: read in the values into an array, sort in place, and print out the array.
2. Matrix Sorting The input is a matrix. Identify a sequence of column interchanges such that in the resulting matrix the rows are all sorted in ascending order. Can every matrix be sorted?
PSK, NSN, DK, TAG CS&E, IIT M 37