cs1100lec05-07

Upload: shellzero

Post on 14-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 cs1100Lec05-07

    1/37

    PSK, NSN, DK, TAGCS&E, IIT M 1

    CS1100Computational Engineering

    Tutors:

    Shailesh Vaya Anurag [email protected] [email protected]

  • 8/2/2019 cs1100Lec05-07

    2/37

    PSK, NSN, DK, TAGCS&E, IIT M 2

    Repetitive StatementsA very important type of statement

    iterating or repeating a set of operations

    - a very common requirement in algorithms

    C offers three iterative constructstheforconstruct

    the while construct

    the do while construct

  • 8/2/2019 cs1100Lec05-07

    3/37

    PSK, NSN, DK, TAGCS&E, IIT M 3

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

  • 8/2/2019 cs1100Lec05-07

    4/37

    PSK, NSN, DK, TAGCS&E, IIT M 4

    The while construct

    General form:

    while ( )

    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!

  • 8/2/2019 cs1100Lec05-07

    5/37

    PSK, NSN, DK, TAGCS&E, IIT M 5

    Repetition Structure - WhileSyntaxwhile (condition){ statement}

    #include

    main()

    { int n, counter, value;

    printf(Enter value for n: );

    scanf(%d, &n);

    counter = 0;

    value = 1; contd..

    Print powers of 2 till 2N

  • 8/2/2019 cs1100Lec05-07

    6/37

    PSK, NSN, DK, TAGCS&E, IIT M 6

    Program using whilecounter = 0; /*repeated*/

    value = 1; /*repeated*/

    printf(current value is %d\n, value);

    while (counter

  • 8/2/2019 cs1100Lec05-07

    7/37

    PSK, NSN, DK, TAGCS&E, IIT M 7

    Testing the program Choose test cases:

    A few normal values: n = 2, 5, 8, 11

    Boundary values: n = 0, 1

    Invalidvalues: 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 theLHS

    Check if the output is expected in each test case

  • 8/2/2019 cs1100Lec05-07

    8/37

    PSK, NSN, DK, TAGCS&E, IIT M 8

    More on Loops

    Two kindssentinel-controlled and counter

    controlled.

    Counterloop runs till counter reaches its limit.

    Use it when the number of repetitions is known.

    Sentinelloop runs till a certain condition is

    encountered. Examplea \n (newline) is

    encountered in the input. Use it when the

    number of repetitions is a property of the inputand not of the problem being solved.

  • 8/2/2019 cs1100Lec05-07

    9/37

    PSK, NSN, DK, TAGCS&E, IIT M 9

    ForloopsCounter 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 byforcan be achieved usingwhile.

    Use offorhelps make the program error free

  • 8/2/2019 cs1100Lec05-07

    10/37

    PSK, NSN, DK, TAGCS&E, IIT M 10

    Theforconstruct

    General form:

    for (expr1; expr2; expr3)

    statement

    Semantics:evaluate expr1 - initialization operation(s)

    repeat - evaluate expression expr2 and

    if expr2 is trueexecute statement and expr3

    else stop and exit the loop

  • 8/2/2019 cs1100Lec05-07

    11/37

    PSK, NSN, DK, TAGCS&E, IIT M 11

    Example

    Replace our previous program by the following

    for (count = 0; count

  • 8/2/2019 cs1100Lec05-07

    12/37

    PSK, NSN, DK, TAGCS&E, IIT M 12

    CS110 Lecture 6

    Shankar Balachandran

    [email protected]

    Shankar Balachandran

    [email protected]

    Sukhendhu Das

    [email protected]

  • 8/2/2019 cs1100Lec05-07

    13/37

    PSK, NSN, DK, TAGCS&E, IIT M 13

    Simple example offorstatementCompute the sum of the first 20 odd numbers

    int i, j, sum;

    sum = 0;

    for (j = 1, i = 1; i

  • 8/2/2019 cs1100Lec05-07

    14/37

    PSK, NSN, DK, TAGCS&E, IIT M 14

    Calculating compound interest

    Principal:1000/-; rate of interest: 5% (p.a); period: 10 yrs

    #include 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

  • 8/2/2019 cs1100Lec05-07

    15/37

    PSK, NSN, DK, TAGCS&E, IIT M 15

    Expected Output :year Amount in the deposit

    1 1050.00

    2 1102.50

    3 1157.62

    4 1215.51

    5 1276.28

    6 1340.10

    7 1407.10

    8 1477.46

    9 1551.33

    10 1628.89

    Space betweenyear and Amount isbecause of \t

    Note that thenumbers arealigned to the right

  • 8/2/2019 cs1100Lec05-07

    16/37

    PSK, NSN, DK, TAGCS&E, IIT M 16

    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 andadd the new digit

  • 8/2/2019 cs1100Lec05-07

    17/37

    PSK, NSN, DK, TAGCS&E, IIT M 17

    An Example

    Termination condition: Stop

    when x becomes zero

    x is the given number

    y is the number being computed

    y = 0 x = 56342

    y = 0*10 + 2 = 2 x = 5634

    y = 2*10 + 4 = 24 x = 563

    y = 24*10 + 3 = 243 x = 56

    y = 243*10 + 6 = 2436 x = 5y = 2436*10 + 5 = 24365 x = 0

  • 8/2/2019 cs1100Lec05-07

    18/37

    PSK, NSN, DK, TAGCS&E, IIT M 18

    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 );x = (x /10);

    }printf("The reversed number is %d \n", y);

    }Exercise: Try this program for n=120, n=1400. Fix problems if there are any.

    Remember integer division

    truncates the quotient

  • 8/2/2019 cs1100Lec05-07

    19/37

    PSK, NSN, DK, TAGCS&E, IIT M 19

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

    main ( )

    {

    int d, n, sum;

    scanf(%d, &n);

    for (sum = 1, d = 2; d

  • 8/2/2019 cs1100Lec05-07

    20/37

    PSK, NSN, DK, TAGCS&E, IIT M 20

    The do while construct

    forand while check termination condition before

    each evaluation of the loop body

    Sometimes - execute the statement and

    check for condition

    General form:

    dostatementwhile (expr)

    Semantics:execute the statementand checkexpr

    ifexpris true, re-execute statementelse exit

  • 8/2/2019 cs1100Lec05-07

    21/37

    PSK, NSN, DK, TAGCS&E, IIT M 21

    CS110 Lecture 7

    Shankar Balachandran

    [email protected]

    Shankar Balachandran

    [email protected]

    Sukhendhu Das

    [email protected]

  • 8/2/2019 cs1100Lec05-07

    22/37

    PSK, NSN, DK, TAGCS&E, IIT M 22

    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 (prevGuesscurrGuess) > error);

    sqRoot = currGuess;

    printf(Square Root = %.10f\n, sqRoot);

    }

  • 8/2/2019 cs1100Lec05-07

    23/37

    PSK, NSN, DK, TAGCS&E, IIT M 23

    Some Sample Outputs

    N = 2

    Current Guess = 1.0000000000

    Current Guess = 1.5000000000

    Current Guess = 1.4166666269

    Current Guess = 1.4142156839

    Square Root = 1.4142135382

    N = 200

    Current Guess = 100.0000000000

    Current Guess = 51.0000000000

    Current Guess = 27.4607849121

    Current Guess = 17.3719482422

    Current Guess = 14.4423809052

    Current Guess = 14.1452569962

    Current Guess = 14.1421356201

    Square Root = 14.1421356201

  • 8/2/2019 cs1100Lec05-07

    24/37

    PSK, NSN, DK, TAGCS&E, IIT M 24

    NewtonRaphson method

    f' denotes the derivative of thefunctionf.

    By simple algebra we can derive:

    http://en.wikipedia.org/wiki/Newton's_method

  • 8/2/2019 cs1100Lec05-07

    25/37

    PSK, NSN, DK, TAGCS&E, IIT M 25

    Repetition Structures

    t

    t

    f

    t

    f

    f

    While StructureDo/WhileStructure

    For StructureSingle Entry

    Single Exit

    expr

    expr

    expr

    body

    body

    body

    init

    incr

  • 8/2/2019 cs1100Lec05-07

    26/37

    PSK, NSN, DK, TAGCS&E, IIT M 26

    Structured ProgrammingTo 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 boxesin 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 asrequired and in any order.

  • 8/2/2019 cs1100Lec05-07

    27/37

    PSK, NSN, DK, TAGCS&E, IIT M 27

    Spaghetti programming1. First line

    2. IF (condition1) Goto 13

    3. Third line

    4. If (condition 2) go to 7

    5. Fourth line

    6. Fifth line

    7. Go to 38. Sixth line

    9. If (condition 3) go to 12

    10. Go to 8

    11. Line number 11

    12. Line 1213. If (condition 4) go to 1

    14. Print (Im done finally !)

    15. End

  • 8/2/2019 cs1100Lec05-07

    28/37

    PSK, NSN, DK, TAGCS&E, IIT M 28

    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 matricescan be multiplied. Print out the decision.

    Write a program that reads in two matrices, and

    multiplies them. Your output should be the twomatrices and the resulting product matrix.

  • 8/2/2019 cs1100Lec05-07

    29/37

    PSK, NSN, DK, TAGCS&E, IIT M 29

    Switch Selection Structure

    In place of the else iffor a multiway selection

    Syntaxif (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

    Syntaxswitch(expression){case const-expr: statements

    case const-expr: statements

  • 8/2/2019 cs1100Lec05-07

    30/37

    PSK, NSN, DK, TAGCS&E, IIT M 30

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

    main()

    { int c, i, nWhite, nOther, nDigit[10];

    nWhite = nOther = 0;

    for(i=0;i

  • 8/2/2019 cs1100Lec05-07

    31/37

    PSK, NSN, DK, TAGCS&E, IIT M 31

    Counting digitscase :

    case\n:case\t: nWhite++; break;

    default: nOther++; break;

    }}

    printf(Digits:\n)

    for(i=0;i

  • 8/2/2019 cs1100Lec05-07

    32/37

    PSK, NSN, DK, TAGCS&E, IIT M 32

    Break and Continue

    break breaks out of the innermost loop or switch

    statement in which it occurs

    continuestarts the next iteration of the loop in

    which it occurs.

    More on this later.

  • 8/2/2019 cs1100Lec05-07

    33/37

    PSK, NSN, DK, TAGCS&E, IIT M 33

    An Array

    A data structure containing items of

    same data type Declaration: array name, storagereservation

    int marks[7] = {22,15,75,56,10,33,45};

    - a contiguous group of memory locationsnamed marks for holding 7 integer items

    - elements/components - variablesmarks[0], marks[1], , marks[6]

    marks[i] i - position / subscript (0

    i

    6)- the value of marks[2] is 75

    - new values can be assigned to elementsmarks[3] = 36;

    22

    15

    75

    56

    10

    33

    45

    0

    1

    2

    3

    4

    5

    6

  • 8/2/2019 cs1100Lec05-07

    34/37

    PSK, NSN, DK, TAGCS&E, IIT M 34

    Example using arraysRead ten numbers into an array and compute their average

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

    }

  • 8/2/2019 cs1100Lec05-07

    35/37

    PSK, NSN, DK, TAGCS&E, IIT M 35

    Polynomial EvaluationEvaluate

    p(x) = anxn

    + an-1xn-1

    + an-2xn-2

    + a1x + a0at a given x value.

    Computing each term and summing upn + (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 additionswill run faster!

  • 8/2/2019 cs1100Lec05-07

    36/37

    PSK, NSN, DK, TAGCS&E, IIT M 36

    Polynomial Evaluation#include

    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 = 0; i--) /* evaluate p(x) */

    value = x*value + coeff[i];

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

  • 8/2/2019 cs1100Lec05-07

    37/37

    PSK NSN DK TAG CS&E IIT M 37

    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 SortingThe input is a matrix. Identify

    a sequence of column interchanges such that in

    the resulting matrix the rows are all sorted inascending order. Can every matrix be sorted?