Engineering Problem Solving with C

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

For loops For loops are controlled by a counter variable. for( c =init_value;c
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
1 Control Structures and Data Files Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
13&14-2 Know the forms of loop statements in C (while,do/while,for). Understanding how data conversion occurs. Read/Write data in files using Unix redirection.
Reviw: Control Structures
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
1 Programming a Computer Lecture Ten. 2 Outline  A quick introduction to the programming language C  Introduction to software packages: Matlab for numerical.
H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
The following statements are for y = -1; if ( x ) if ( x>0 ) y = 1; else y = 0; A. y= -1 x0 B. y= 0 x0 C. y= 1 x
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Simple C Programs.
ECE Application Programming
ALGORITHMS AND FLOWCHARTS
CS1010 Programming Methodology
CSE 220 – C Programming Loops.
REPETITION CONTROL STRUCTURE
Control Structures and Data Files
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Lecture 7: Repeating a Known Number of Times
C Program Controls + Flow Structure
Chapter 4 (Conditional Statements)
Engineering Problem Solving with C++, Etter/Ingber
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Lecture 13 & 14.
Repetition-Counter control Loop
Engineering Problem Solving with C Fundamental Concepts
CSE1320 INTERMEDIATE PROGRAMMING Operators+Conditionals+Loop
Selection and Repetition (Loop) Chapter 4 and 5
CSI 121 Structure Programming Language Lecture 10: Iteration (Part 1)
Control Structures Lecture 7.
Chapter 13 Control Structures
Looping.
Arrays, For loop While loop Do while loop
Chapter 13 Control Structures
If statement.
How to develop a program?
Chapter 7 Additional Control Structures
Structured Program
Chapter 4 - Program Control
Loops in C.
3 Control Statements:.
Repetition and Loop Statements
Week 6 CPS125.
UMBC CMSC 104 – Section 01, Fall 2016
Computer Programming Techniques Semester 1, 1998
Computer programming Lecture 3.
EPSII 59:006 Spring 2004.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
ICS103: Programming in C 5: Repetition and Loop Statements
Chapter 13 Control Structures
Presentation transcript:

Engineering Problem Solving with C CSCI-125/ENGR-144 Engineering Problem Solving with C Ch 3

3.1 Algorithm Development So far, we considered very simple programs (read, compute, print) Top-down Design Start from the big picture Use a process called divide-and-conquer Keep dividing the problem until steps are detailed enough to convert to a program Refinement with Pseudo-code (English like statements) and Flowchart (diagram, graph)

Pseudo-code Notation and Flowchart Symbols

Structured Programming Use simple control structures to organize the solution to a problem Sequence Selection Repetition yes no yes no

Sequence

Selection

Repetition

Extras Evaluation of alternative solution Error condition A problem can be solved in many different ways Which is the best (e.g, faster, less memory req) Error condition Do not trust user! Check the data. A=b/c; Be clear about specifications Generation of Test Data Test each of the error conditions Program validation and verification Program walkthrough

3.2 Conditional Expressions Selection and repetition structures use conditions, so we will first discuss them A condition is an expression (e.g., x= a > b) that can be evaluated to be TRUE (any value > 0) or FALSE (value of 0) Conditional Expression is composed of expressions combined with relational and/or logical operators

Relational Operators == equality (x == 3) != non equality (y != 0) < less than (x < y) > greater than (y > 10) <= less than equal to (x <= 0) >= greater than equal to (x >= y) !!! a==b vs. a=b !!!

Examples A < B fabs(denum) < 0.0001 D = b > c; if (D) A=b+c; 4 2 -0.01 ? 6 1 10 A B denum D b c X Y K A < B fabs(denum) < 0.0001 D = b > c; if (D) A=b+c; Mixing with arithmetic op X+Y >= K/3

Logical Operators ! not !(x==0) && and (x>=0) && (x<=10) || or (x>0) || (x<0) A B A && B A || B !A !B False True

Examples A<B && C>=5 A+B * 2 < 5 && 4>=A/2 A<B || C<B && A-2 < 10 A < B < C ???? A<B<C is not the same as (A<B) && (B<C) 4 2 6 A B C

Precedence for Arithmetic, Relational, and Logical Operators

Exercise Assume that following variables are declared a = 5.5 b = 1.5 k = -3 Are the following true or false a < 10.0 + k a + b >= 6.5 k != a-b !(a == 3*b) a<10 && a>5 fabs(k)>3 || k<b-a

Exercise Assume that following variables are declared x = 3.0 y = 4.0 z = 2.0 flag = 0 Are the following true or false x > z && y > z x+ y/z <= 3.5 z > x || z > y !flag x == 1.0 || x == 3.0 z < x && x < y x <= z || x >= y !flag || y + z >= x – z !(flag || y + z >= x – z)

Exercise Assume that following variables are declared a = 5 b = 10 c = 15 flag =1 Are the following true or false C == a + b || !flag a != 7 && flag || c >=6 ! (b < = 12) && a%2 ==0 ! ( a > 5 || c < a +b )

3.3 Selection Statements if if else switch

if statement if(Boolean expression) statement; /* single statement */ /* more than one statement */ statement1; … statement n; }

if statement - examples if (x > 0) k++; if(x > 0) { y = sqrt(x); } if(x > 0) /* a common mistake */ Name Addr Content x 9 y 5 k 4

if else statement if(Boolean expression) statement; else statement block } else { }

if else statement if (x > y) temp = x; else temp = y; What does the following program do? Assume that x, y, temp are declared. if (x > y) temp = x; else temp = y; Name Addr Content x 9 y 5 temp ? if (x > y){ temp = x; } else { temp = y; }

Exercise Write an if-else statement to find both the maximum and minimum of two numbers. Assume that x, y, min, max are declared. if (x > y) { max = x; min = y; } else { max = y; min = x; } Name Addr Content x y max ? min 9 5 3 8 9 5 3 8 6 8 3 6

if else statement Split the following statement into two separate if if (x > y) temp = x; else temp = y; if (x > y) temp = x; if (x <= y) temp = y;

Flow chart for previous slide if (x > y) temp = x; if (x <= y) temp = y; if (x > y) temp = x; else temp = y; x > y T temp=x x > y T x <= y T temp=y temp=x temp=y

if else statement (Exercise) Give the final value of x if the initial value x is 1 if (x >= 0) x = x+1; Else if (x >=1) x = x+2; if (x >= 0) x = x+1; if (x >= 1) x= x+2;

nested if-else if(x > y) if(y < z) k++; else m++; j++; } j++; F x > y T T y < z j++ F k++ m++

Exercise int x=9, y=7, z=2, k=0, m=0, j=0; if(x > y) if(y < z) else m++; j++; What are the values of j, k and m?

Exercise: Find the value of a a =a+3 a < 500 a =a*2 a =a*10 T int a = 750; if (a>0) if (a >= 1000) a = 0; else if (a <500) a =a*2; a =a*10; a =a+3;

Exercise: Find the value of a int a = 750; if (a>0) { if (a >= 1000) { a = 0; } else { if (a <500) { a =a*2; a =a*10; } a =a*3; a > 0 a >= 1000 a = 0 a =a+3 a < 500 a=a*2 a =a*10 T

Indentation int a = 750; if (a>0) if (a >= 1000) a = 0; else Good Not good

Nested if What is the difference, if any? if( expression1 ) statement1; else statement2; if( expression1 ) if( expression2 ) statement1; else statement2; No difference! Spacing is only important to us to make the program readable, not to the compiler.

Indentation (cont’d) What is the output of the following programs int a = 5, b = 3; if (a>10) a = 50; b = 20; printf(" a = %d, b = %d\n",a, b); if (a>10) { a = 50; b = 20; } printf(" a = %d, b = %d\n",a, b); Not good if (a>10) a = 50; b = 20; printf(" a = %d, b = %d\n",a, b); if (a>10) { a = 50; b = 20; } printf(" a = %d, b = %d\n",a, b); Good

Switch Statement switch(expression) { case constant: statement(s); break; default: /* default is optional */ }

Switch Statement switch (op_code) { Expression must be of type integer or character The keyword case must be followed by a constant break statement is required unless you want all subsequent statements to be executed. switch (op_code) { case ‘N’: printf(“Normal\n”); break; case ‘M’: printf(“Maintenance Needed\n”); default: printf(“Error\n”); }

Exercise Convert the switch statement into if statement. switch (op_code) { case ‘N’: printf(“Normal\n”); break; case ‘M’: printf(“Maintenance Needed\n”); default: printf(“Error\n”); } if (op_code == ‘N’) printf(“Normal\n”); else if (op_code == ‘M’) printf(“Maintenance Needed\n”); else printf(“Error\n”);

/* determine average life expectancy of a standard light bulb */ switch (watts) { case 25: life = 2500; break; case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; }

Exercise Convert the following nested if/else statements to a switch statement if (rank==1 || rank==2) printf("Lower division \n"); else { if (rank==3 || rank==4) printf("Upper division \n");   {  if (rank==5) printf("Graduate student \n"); printf("Invalid rank \n"); } switch(rank) { case 1: case 2: printf("Lower division \n"); break; case 3: case 4: printf("Upper division \n"); case 5: printf("Graduate student \n"); default: printf("Invalid rank \n"); }

with this section of code? char a, b, c, d, f, grade; int actr, bctr, cctr, dctr, fctr, ictr; printf(“Enter letter grade: “); scanf(“%c”, &grade); switch (grade) { case a: ++actr; break; case b: ++bctr; case c: ++cctr; case d: ++dctr; case f: ++fctr; default: ++ictr; } /* given these declarations */ What’s wrong with this section of code? Answer: counters not initialized case needs constants, not variables Not using constants for each case will cause compiler error Not initializing counter variables is logical error, but will NOT cause compiler error

More selection examples

Exercise: Assign Letter Grade Given a score and the following grading scale write a program to find the corresponding grade. 90-100 A 80-89 B 70-79 C 60-69 D 0-59 F

Solution-1 grade = 'A'; else if ((score >= 80) && (score <= 89)) grade = 'B'; else if ((score >= 70) && (score <= 79)) grade = 'C'; else if ((score >= 60) && (score <= 69)) grade = ‘D'; else if ((score >= 0) && (score <= 59)) grade = ‘F'; else printf("Invalide Score\n");

Solution-2 if ((score >= 0) && (score <= 100)) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = ‘D'; else grade = ‘F'; printf("Invalide Score\n");

Exercise: Region in a plane Write a program that reads a point (x, y) from user and prints its region For example Enter x y: 3 -1 This point is in Region 4 Enter x y: -1 -5 This point is in region 3 Enter x y: 0 5 ??????? Region 1 Region 2 Region 4 Region 3

Exercise: The Roots Write a program to ask users to input the coefficients (a, b, c) of a quadratic equation ax^2+bx+c=0, then compute its roots. Example: a = 1, b = -5, c = 6 a=1, b=2, c=2 a = 0, b = 2, c = 4 a=0, b=0, c=0

Exercise: which task takes more time Suppose we have two tasks A and B A takes x hours, y minutes, and z seconds B takes X hours, Y minutes, and Z seconds User enters x, y, z and X, Y, Z Write if-else statements to print out which task takes more time?

Triangle inequality Suppose we want to check if we can make a triangle using a, b, c |a-b| <= c |a-c| <= b |b-c| <= a a+b >= c a+c >= b b+c >= a c a b

Max, Min, Median Write a program that reads 3 numbers a, b and c from user and computes minimum, median and maximum of the numbers. Example: a = 2, b = 5, c = 3 minimum = 2, maximum = 5, median = 3 a = 2, b = 2, c = 3 minimum = 2, maximum = 3, median = 2

Charge for money transfer Suppose you transfer $N and bank’s charge occurs as follows. Write a program that reads N and computes cost

Compute Queuing Delay Write C program that computes and prints out average delay in a queuing system, where the average delay is given as follows

Spell out a number in text using if-else and switch Write a program that reads a number between 1 and 999 from user and spells out it in English. For example: 453  Four hundred fifty three 37  Thirty seven 204  Two hundred four

Loop (Repetition) Structures

Problem: Conversion table degrees  radians Degrees to Radians 0 0.000000 10 0.174533 20 0.349066 30 0.523599 … 340 5.934120 350 6.108653 360 6.283186 radians = degrees * PI / 180;

Sequential Solution #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); degrees = 0; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees = 10; degrees = 20; … degrees = 360; } degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); Not a good solution

Loop Solution #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); while (degrees <= 360) { radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees += 10; } degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees+=10 means degrees= degrees+10

Loop (Repetition) Structures while statement do while statement for statement Two new statements used with loops break and continue

while statement while(expression) statement; while(expression) { … }

Example #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); while (degrees <= 360) radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees += 10; } return 0;

while() Scanf(“%d”, &n); ev=0; while (ev < n) { printf(“%3d\n”, ev); ev +=2; } printf(“\n”); what is displayed by this program for an input of 10? while() i = 0; while ( i <= 5 ) { printf(“%3d%3d\n”, i, 10-i); i +=1; } Predict the output? Printf(“Enter an integer>”); scanf(“%d”, &x); product=x; count =0; while (count < 4) { printf(“%d\n”, product); product *=x; count +=1; } Output values if a data value 5? 6? 7? No, the results are different. Step through the code and see.

Sample C Code scanf in while while(( vals = scanf( “%lf%c%lf”, &op1, &action, &op2)) == 3 ) scanf statement result stored here; optional this value compared to A scanf() is done, accepting a double (long float), a char, and a double. The scanf() function returns the number of successful scans completed, which may be stored in a variable for later examination (rarely) or simply tested directly (e.g., remove the 'vals ='). Regardless, the expression is tested for its value, which in this case is the value returned by scanf(), which is also the value assigned to vals. That value is compared to the value 3, and if equal (that is, the expression value is equal to 3), the while() loop continues. Otherwise, the loop is exited. If the inputs are 35.6c9.3 and 34.7bb, what are output for vals = scanf( “%lf%c%lf”, &op1, &action, &op2)

do while do statement; while(expression); do { statement1; statement2; ... } while(expression); note - the expression is tested after the statement(s) are executed, so statements are executed at least once.

Example #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); do radians = degrees*PI/180; printf("%6i %9.6f \n",degrees,radians); degrees += 10; } while (degrees <= 360); return 0; }

while() vs do while() int x = 10, y = 1; while ( x < 10 ) { if( x == 10 ) y = x; ++x; } printf(“x = %d\n”, x); printf(“y = %d\n”, y); int x = 10, y = 1; do { if( x == 10 ) y = x; ++x; } while ( x < 10 ); printf(“x = %d\n”, x); printf(“y = %d\n”, y); No, the results are different. Step through the code and see. Do these produce the same result?

for statement for(initialization ; test ; increment or decrement ) { … }

Example #include <stdio.h> #define PI 3.141593 int main(void) { int degrees; double radians; printf("Degrees to Radians \n"); for (degrees=0; degrees<=360; degrees+=10) radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); } return 0;

for statement initialize test Increment or decrement true statement(s)

Difference? for(i=0; i<5; i++) printf("%d", i); int i = 0; while(i < 5) { printf("%d", i); i++; } ++i; int i = 0; int j = i; while(j < 5) { printf("%d", i); j = ++i; } int i = 0;int j = i; j = i++;

Increment and Decrement Operators Increment Operator ++ post increment x++; pre increment ++x; Decrement Operator -- post decrement x--; pre decrement --x; } x=x+1; } x=x-1; But, the difference is in the following example. Suppose x=10; A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11 B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11

Examples ? 5 1 3 1 5 7 i sum n fact 1 4 9 int sum =0, i; for( i=1 ; i < 7;i=i+2 ){ sum = sum+i; } int fact=1, n; for( n=5 ; n>1 ; n--){ fact = fact * n; ? 5 1 3 1 5 7 i sum n fact 1 4 9 n--; means n=n-1; n++; means n=n+1;

Example What will be the output of the following program, also show how values of variables change in the memory. int sum1, sum2, k; sum1 = 0; sum2 = 0; for( k = 1; k < 5; k++) { if( k % 2 == 0) sum1 =sum1 + k; else sum2 = sum2 + k; } printf(“sum1 is %d\n”, sum1); printf(“sum2 is %d\n”, sum2); 0 2 6 0 1 4 1 2 3 4 5 sum1 sum2 k sum1 is 6 sum2 is 4

Exercise for (k=3; k<=10; k++) { statements; } Determine the number of times that each of the following for loops are executed. for (k=3; k<=10; k++) { statements; } for (k=5; k<=83; k+=4) { for (count=20; count>=0; count=count-2) {

for() loop example How many times does the body loop? For (count =0; count <=n; ++ count) { sum +=count; } if want to execute the loop body n times, how to change code? sum=0; k=1; for (i = -n; i < n-k; ++i) sum +=i*i;

for() loop example Trace the following program segment: j=10; for (i=1; i<=5; ++i) { printf(“%d %d \n”, i, j); j -=2; } Rewrite the previous program segment so that it produced the same output but uses 0 as the initial value of i ?

for() Logic of for() is like that of while() Compare the code: int ctr; for( ctr = 1; ctr < 10; ++ctr ) printf(“Ctr = %d\n”, ctr); int ctr; ctr = 1; while ( ctr < 10 ) { printf(“Ctr = %d\n”, ctr); ++ctr; } Both segments of code do the same thing in the same order. Always think of the test in the middle expression of a for() as the same as a while(), because it works the same way.

For vs. while loop (Exercise) Convert the following for loop to while loop for( i=5; i<10; i++) { pritntf(“ i = %d \n”, i); } i=5; while(i<10){ i++;

More loop examples

/* Counting down to blast-off */ #include <stdio.h> int main(void) { int time, start; printf("Enter starting time (an integer) in seconds> "); scanf("%d", &start); printf("\nBegin countdown\n"); for (time = start; time > 0; time -= 1) { printf("T - %d\n", time); } printf("Blast-off!\n"); return (0); Enter starting time (an integer) in seconds> 5 Begin countdown T - 5 T - 4 T - 3 T - 2 T - 1 Blast-off!

for() loop example Trace the execution of the loop that follows for n=8. Show the values of odd and sum after the update of the loop counter for each iteration? sum=0; for (odd = 1; odd < n; odd += 2) sum +=odd; printf(“Sum of positive odd numbers less than %d is %d.\n”, n,sum)

Example Write a program that prints in two columns n even numbers starting from 2, and a running sum of those values. For example suppose user enters 5 for n, then the program should generate the following table: Enter n (the number of even numbers): 5 Value Sum 2 2 4 6 6 12 8 20 10 30

#include <stdio.h> int main(void) { /* Declare variables. */ int n; int sum, i; printf("Enter n "); scanf("%d",&n); printf("Value \t Sum\n"); sum = 0; for(i=1; i <=n; i++){ sum = sum + 2*i; printf("%d \t %d\n", 2*i, sum); } return 0;

Nested loop examples

a for() loop initialize variables i, j, and k each to 1 test to end loop when i > 10 or j > 3 * k increment i by 1, j by 2, and k by 2 * i print i, j, and k in the body of the loop expression 1 expression 2 expression 3 for ( i = 1, k = 1, j = 1; i <= 10 && j <= 3 * k ; ++i, j += 2, k += 2 * i ) printf(“i = %d, j = %d, k = %d\n”, i, j, k); initialize variables the first section of the for() statement is done only once, so variable initialization is typically done here. Note the use of the comma operator! i = 1, j = 1, k = 1; sets each to 1 could also have done i=j=k=1; without using the comma operator. test to end loop but the for() loop test for a non-zero result to continue the loop! So the logic must be inverted. Ending the loop when i > 10 means the same as continuing the loop while i <= 10; ending the loop when j > 3*k means the same as continuing the loop while j <= 3*k. Ending the loop when condition-1 or condition-2 occurs means the same as continuing the loop while condition-1 and condition-2 are both true. Do not use comma operator here; use only single or compound expressions. incrementing the counters ++i adds 1 to i j+=2 adds to to k (same as j = j + 2) k+=2*i adds 2*i to k (as in k = k + 2*i) note the use of the comma operator; order here is important, for k gets the value of the incremented i*2; if k+=2*i were placed before the ++i, then the old value of i would have been used! print the results in the body of the for() loop Note the use of the comma operator in expression 1 and expression 3. Do not use comma operator in expression 2.

Exercise What is the output of the following program? for (i=1; i<=5; i++) { for (j=1; j<=4; j++){ printf(“*”); } printf(“\n”); Output ****

for() loop example How many lines of asterisks are displayed? for (i= 0; i < 10; ++i) for (j=0; j < 5; ++j) printf(“**********\n”); for (row= 1; row <=10; row++) { for (col=1; col<= 10; col++) { printf(“%4d\n”, row*col); }

Exercise What is the output of the following program? for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”); Output * ** *** **** *****

Exercise: Modify the following program to produce the output. for (i=A; i<=B; i++) { for (j=C; j<=D; j++) { printf(“*”); } printf(“\n”); Output ***** **** *** ** *

for() loop example How many times for the first printf? How many times for the second printf? What is the last value displayed? For (i = 0; i < 7; ++i ) { for ( j =0; j < i; ++j ) printf(%4d”, i*j); printf(“\n”); }

Example: nested loops to generate the following output int i, j; for(i=1; i <= 5; i++){ printf("i=%d ", i); for(j=1; j <= i; j++) { if (i % 2 == 0) printf("+ "); else printf("* "); } printf("\n"); int i, j; for(i=1; i <= 5; i++){ printf("i=%d ", i); for(j=1; j <= i; j++) { if (i % 2 == 0) printf("+ "); else printf("* "); } printf("\n"); What/how do you need to change in th following program? for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”);

Exercise Write a program using loop statements to produce the following output. Output * ** *** **** *****

Compute xy when y is integer Suppose we don’t have pow(x,y) and y is integer, write a loop to compute xy printf(“Enter x, y :”); scanf(“%d %d”, &x, &y); res=1; for(i=1; i<=y; i++){ res = res * x; }

Exercise: sum Write a program to compute the following Enter n Enter n total=0; for(i=1; i<=n; i++) total = total + 2 * i ; print total Enter n total=0; for(i=1; i<=n; i++) total = total + i ; print total

Exercise: sum Write a program to compute the following Enter x and m total=0; sofarx=1; for(i=0; i<=m; i++) { total = total +sofarx; sofarx = sofarx * x; } print total Enter x and m total=0; for(i=0; i<=m; i++) total = total + pow(x, i); print total

Exercise: ln 2 Write a program to compute the following Enter n ln2=0; for(i=1; i<=n; i++) if ( i % 2 == 0) ln2 = ln2 - 1.0 / i; else ln2 = ln2 + 1.0 / i; print total

Exercise: ex Write C program that reads the value of x and n from the keyboard and then approximately computes the value of ex using the following formula: Then compare your approximate result to the one returned by exp(x) in C library, and print out whether your approximation is higher or lower.

int i, n; double x, ex; double powx, fact; printf("Enter the value of x and n : "); scanf("%lf %d",&x, &n); /* Write a loop to compute e^x using the above formula */ ex=1.0; fact=1.0; powx=1.0; for(i=1; i<=n; i++){ powx = powx * x; fact = fact * i; ex = ex + powx / fact; } printf("Approx value of e^x is %lf when n=%d\n",ex, n);

Exercise: sin x Compute sin x using printf(“Enter x n :”); scanf(“%lf %d”, &x, &n); total=0; powx=x; factx=1; for(i=0; i <= n; i++){ k= 2*n+1; if (i%2==0) total= total - powx/factx; else total= total + powx/factx; powx= powx * x * x; factx = factx * k * (k-1); } printf( “sin(%lf) is %lf\n”,x, total);

break statement break; terminates loop execution continues with the first statement following the loop sum = 0; for (k=1; k<=5; k++) { scanf(“%lf”,&x); if (x > 10.0) sum +=x; } printf(“Sum = %f \n”,sum); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0) break; sum +=x; k++; } printf(“Sum = %f \n”,sum);

continue statement continue; forces next iteration of the loop, skipping any remaining statements in the loop sum = 0; for (k=1; k<=5; k++) { scanf(“%lf”,&x); if (x > 10.0) sum +=x; } printf(“Sum = %f \n”,sum); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0){ k++; continue; } sum +=x; printf(“Sum = %f \n”,sum); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0) continue; sum +=x; k++; } printf(“Sum = %f \n”,sum);

Example: what will be the output int main() { int a, b, c; a=5; while(a > 2) { for (b = a ; b < 2 * a ; b++ ) { c = a + b; if (c < 8) continue; if (c > 11) break; printf( “a = %d b = %d c = %d \n”, a, b, c); } /* end of for-loop */ a--; } /* end of while loop */ } a = 5 b = 5 c = 10 a = 5 b = 6 c = 11 a = 4 b = 4 c = 8 a = 4 b = 5 c = 9 a = 4 b = 6 c = 10 a = 4 b = 7 c = 11 a = 3 b = 5 c = 8

Example: break and continue int ctr = 0; while( ctr < 6 ) { if( ctr < 3 ) ctr += 2; printf(“%d\n”, ctr); continue; } else printf(“%d\n”, ++ctr); break; printf(“Bottom of loop\n”); What is printed? 2 4 5 Why is "bottom of loop" skipped? Prints 2 4 5 Does NOT print “Bottom of loop”. That code is unreachable!

For vs. while loop : Convert the following for loop to while loop for( i=5; i<10; i++) { printf(“AAA %d \n”, i); if (i % 2==0) continue; pritntf(“BBB %d \n”, i); } i=5; while(i<10) { printf(“AAA %d \n”, i); if (i % 2==0) { i++; continue; } pritntf(“BBB %d \n”, i);

Example: A man walks Suppose a man (say, A) stands at (0, 0) and waits for user to give him the direction and distance to go. User may enter N E W S for north, east, west, south, and any value for distance. When user enters 0 as direction, stop and print out the location where the man stopped N E S W

float x=0, y=0; char direction; float distance; while (1) { printf("Please input the direction as N,S,E,W (0 to exit): "); scanf("%c", &direction); fflush(stdin); if (direction=='0'){ /*stop input, get out of the loop */ break; } if (direction!='N' && direction!='S' && direction!='E' && direction!='W') { printf("Invalid direction, re-enter \n"); continue; printf("Please input the mile in %c direction: ", direction); scanf ("%f", &distance); fflush(stdin); if (direction == 'N'){ /*in north, compute the y*/ y = y + distance; } else if (direction == 'E'){ /*in east, compute the x*/ x = x + distance; } else if (direction == 'W'){ /*in west, compute the x*/ x= x - distance; } else if (direction == 'S'){ /*in south, compute the y*/ y = y- distance; printf("\nCurrent position of A: (%4.2f, %4.2f)\n", x, y); /* output A's location */