0% found this document useful (0 votes)
53 views37 pages

Cs1100lec05 07

This document provides information about the CS1100 Computational Engineering course offered at IIT Madras. It discusses repetitive statements in programming and covers various iterative constructs like for, while, and do-while loops. It provides examples of using these loops and emphasizes the importance of structured programming. It also discusses other related topics like switch statements, testing programs, and exercises involving loops.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views37 pages

Cs1100lec05 07

This document provides information about the CS1100 Computational Engineering course offered at IIT Madras. It discusses repetitive statements in programming and covers various iterative constructs like for, while, and do-while loops. It provides examples of using these loops and emphasizes the importance of structured programming. It also discusses other related topics like switch statements, testing programs, and exercises involving loops.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

CS1100 Computational Engineering

Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

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

the for construct


the while construct

the do while construct

PSK, NSN, DK, TAG CS&E, IIT M

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

PSK, NSN, DK, TAG CS&E, IIT M

The while construct


General form: while ( <expr> ) <statement> Semantics: repeat: Evaluate the expr. If the expr is true execute the statement else exit the loop. expr must be modified in the loop or we have an infinite loop!
PSK, NSN, DK, TAG CS&E, IIT M 4

Repetition Structure - While


Syntax while (condition){ statement} #include<stdio.h> Print powers of 2 till 2N main() { int n, counter, value; printf(Enter value for n: ); scanf(%d, &n); counter = 0; value = 1; contd..
PSK, NSN, DK, TAG CS&E, IIT M 5

Program using while


counter = 0; /*repeated*/ value = 1; /*repeated*/ printf(current value is %d \n, value); while (counter <= n)

{
value = 2 * value; printf(current value is %d \n, value);

counter = counter + 1;
} }

Exercise: try this program and identify problems


PSK, NSN, DK, TAG CS&E, IIT M 6

Testing the program


Choose test cases:
A few normal values: n = 2, 5, 8, 11 Boundary values: n = 0, 1 Invalid values: n = -1

Hand simulate the execution of the program


On paper, draw a box for each variable and fill in the initial values (if any) Simulate execution of the program one statement at a time For any assignment, write the new value of the variable in the LHS Check if the output is expected in each test case
PSK, NSN, DK, TAG CS&E, IIT M 7

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

The for construct


General form: for (expr1; expr2; expr3) statement Semantics: evaluate expr1 - initialization operation(s) repeat - evaluate expression expr2 and if expr2 is true execute statement and expr3 else stop and exit the loop
PSK, NSN, DK, TAG CS&E, IIT M 10

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]

PSK, NSN, DK, TAG CS&E, IIT M

12

Simple example of for statement


Compute the sum of the first 20 odd numbers int i, j, sum; Set j to the first odd number; Note the comma separating the initializations sum = 0; i : Loop control variable for (j = 1, i = 1; i <= 20; i++) Termination condition { sum += j; Increment sum by the ith odd number j += 2; Set j to the next odd number } The for construct expr1, expr2, expr3
-- involving the loop control variable only
PSK, NSN, DK, TAG CS&E, IIT M 13

Calculating compound interest


Principal:1000/-; rate of interest: 5% (p.a); period: 10 yrs
#include <stdio.h> main( ){ int yr; double amt, principal = 1000.0, rate = .05; amt = principal; printf(%4s\t%21s\n, year, Amount in the deposit); for (yr = 1; yr < = 10; yr++) { amt += amt * rate; printf(%4d\t%21.2f\n, yr, amt); String constants used to align heading and } output data in a table }
PSK, NSN, DK, TAG CS&E, IIT M 14

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

Space between year and Amount is because of \t

1 2 3 4

Note that the numbers are aligned to the right

5 6 7 8 9 10

PSK, NSN, DK, TAG CS&E, IIT M

Example for while construct


Print the reverse of a given integer: 234 432 Method: Till the number becomes zero, extract the last digit - number modulo 10 make it the next digit of the result - multiply the current result by 10 and add the new digit
PSK, NSN, DK, TAG CS&E, IIT M 16

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

PSK, NSN, DK, TAG CS&E, IIT M

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

Perfect number detection


Perfect number: sum of proper divisors add up to the number

main ( ) { int d, n, sum; scanf(%d, &n); for (sum = 1, d = 2; d <= (n/2); d++) { if (n%d == 0) sum += d; }

d<n will also do, but would do unnecessary work

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

Exercise: Modify to find the first n perfect numbers


19

The do while construct


for and while check termination condition before each evaluation of the loop body Sometimes - execute the statement and check for condition General form: do statement while (expr) Semantics: execute the statement and check expr if expr is true, re-execute statement else exit
PSK, NSN, DK, TAG CS&E, IIT M 20

CS110 Lecture 7
Shankar Balachandran [email protected] Sukhendhu Das [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

21

Square root of a number (Babylonian Method)


main( ) { int n; float prevGuess, currGuess, error, sqRoot; scanf(%d, &n); currGuess = (float) n/2 ; error = 0.0001; do { printf(Current Guess = %.10f\n,currGuess); prevGuess = currGuess; currGuess = ( prevGuess + n / prevGuess) / 2; } while (fabs (prevGuess currGuess) > error); sqRoot = currGuess; printf(Square Root = %.10f\n, sqRoot);
PSK, NSN, DK, TAG CS&E, IIT M

22

Some Sample Outputs


N=2 Current Guess = 1.0000000000 N = 200
Current Guess = 100.0000000000 Current Guess = 51.0000000000 Current Guess = 27.4607849121 Current Guess = 17.3719482422 Current Guess = 14.4423809052

Current Guess = 1.5000000000


Current Guess = 1.4166666269 Current Guess = 1.4142156839 Square Root = 1.4142135382

Current Guess = 14.1452569962


Current Guess = 14.1421356201 Square Root = 14.1421356201

PSK, NSN, DK, TAG CS&E, IIT M

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

Single Entry Single Exit


PSK, NSN, DK, TAG CS&E, IIT M

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

PSK, NSN, DK, TAG CS&E, IIT M

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

Switch Selection Structure


In place of the else if for a multiway selection Syntax if (condition_1){execute these} else if (condition_2) {execute these} else if (condition_3) {execute these} and so on.. Switch replaces else if for a very special case Syntax switch(expression){ case const-expr: statements case const-expr: statements
PSK, NSN, DK, TAG CS&E, IIT M 29

Counting digits in text (Kernighan & Ritchie, p.59)


#include<stdio.h> An array of ten integers main() { int c, i, nWhite, nOther, nDigit[10]; nWhite = nOther = 0; c declared as int but is read using for(i=0;i<10;i++) nDigit[i]=0;
getchar() though

while((c = getchar()) ! = EOF){ switch(c){ case0:case1:case2:case3:case4:case5: case6:case7:case8:case9: nDigit[c-0]++; break;


PSK, NSN, DK, TAG CS&E, IIT M

Seems to be integer character ?!

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

Break and Continue


break breaks out of the innermost loop or switch statement in which it occurs continue starts the next iteration of the loop in which it occurs. More on this later.

PSK, NSN, DK, TAG CS&E, IIT M

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

- the value of marks[2] is 75 - new values can be assigned to elements


marks[3] = 36;
PSK, NSN, DK, TAG CS&E, IIT M

45

Example using arrays


Read ten numbers into an array and compute their average #include <stdio.h> main(){ int numbers[10], sum = 0, i; float average; for ( i = 0; i < 10; i++) scanf(%d, &numbers[i]); for ( i = 0; i < 10; i++) sum = sum + numbers[i]; average = (float) sum/10; printf(The average of numbers is: %f, average); return 0 /* should be there in all programs */ }
PSK, NSN, DK, TAG CS&E, IIT M 34

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

printf(The value of p(x) at x = %d is %d\n, x, value);

PSK, NSN, DK, TAG CS&E, IIT M

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

You might also like