Computer Programming Techniques Semester 1, 1998

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Advertisements

Chapter 3 - Structured Program Development
Control Structures in C++ while, do/while, for switch, break, continue.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
CMSC 104, Version 8/061L15Switch.ppt The switch Statement Topics Multiple Selection switch Statement char Data Type and getchar( ) EOF constant Reading.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Fundamentals of C and C++ Programming Control Structures and Functions.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Real World Applications: Statistical Measures Problem (page 95-98) Read a series of floating-point numbers from the standard input, and print a statistical.
EC-111 Algorithms & Computing Lecture #4 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
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.
C Lecture Notes 1 Structured Program Development.
Assignment Operators = +=-= *= /=%= Statement Equivalent Statement a = a + 2 ;a += 2 ; a = a - 3 ;a -= 3 ; a = a * 2 ;a *= 2 ; a = a / 4 ; a /= 4 ; a =
Spring 2005, Gülcihan Özdemir Dağ Lecture 5, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 5 Outline 5.0 Revisiting.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Program to calculate product of odd numbers b/w 1 and 15 #include main() { int prod = 1, x; for(x = 1; x
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
CMSC 104, Version 9/011 The switch Statement Topics Multiple Selection switch Statement char Data Type and getchar( ) EOF constant Reading Section 4.7,
Chapter 1 Basic C Programming
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline Counter-Controlled Repetition: Example Sentinel-Controlled Repetition:
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Dale Roberts Program Control Department of Computer and Information Science, School of Science, IUPUI Fall 2003 CSCI 230 Dale Roberts, Lecturer
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Algorithm: procedure in terms of
Computer Science 210 Computer Organization
ECE Application Programming
Chapter 4 C Program Control Part I
Chapter 4 - Program Control
Week 4 – Repetition Structures / Loops
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
CSI 121 Structure Programming Language Lecture 10: Iteration (Part 1)
Control Structures Lecture 7.
Computer Science 210 Computer Organization
CS1100 Computational Engineering
- Additional C Statements
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Structured Program
Chapter 3 - Structured Program Development
The switch Statement Topics Multiple Selection switch Statement
Chapter 2.1 Repetition.
Assignment Operators Topics Increment and Decrement Operators
Program Control Topics While loop For loop Switch statement
Chapter 3 - Structured Program Development
Assignment Operators Topics Increment and Decrement Operators
switch Selection Structure
2.6 The if/else Selection Structure
EPSII 59:006 Spring 2004.
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
More Loops Topics Counter-Controlled (Definite) Repetition
ECE 103 Engineering Programming Chapter 18 Iteration
Chapter 4 - Program Control
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
The switch Statement Topics Multiple Selection switch Statement
UMBC CMSC 104 – Section 01, Fall 2016
Assignment Operators Topics Increment and Decrement Operators
EECE.2160 ECE Application Programming
More Loops Topics Counter-Controlled (Definite) Repetition
Chapter 13 Control Structures
Presentation transcript:

240-222 Computer Programming Techniques Semester 1, 1998 2. Control Flow Section 3.10 Objectives of these slides: to introduce the main kinds of C control flow

Overview 1. Three/Four Kinds of Control Flow 2. The if Statement 3. The while Statement 4. Grades Average Example 5. Incrementing and Decrementing continued

6. Counter-controlled Repetition 7. The for Statement 8. The switch Statement 9. The break Statement 10. More Complex Input

1. Three/Four Kinds of Control Flow sequence choice (branches) e.g. if and switch statements loops (iteration) e.g. while and for statements recursion

2. The if statement : scanf("%d", &grade); if (grade >= 60) printf("Passed\n"); else { printf("Failed\n"); printf("Repeat Course\n"); } scanf("%d", &grade); :

: if (temp < 0) setting = setting + 20; else if (temp < 10) setting = setting + 10; else setting = setting + 1; :

2. The while statement (sum.c) /* sum between 1 and 10 */ #include <stdio.h> int main() { int i = 1, sum = 0; while (i <= 10) { sum = sum + i; i = i + 1; } printf("Sum is %d\n", sum); return 0; }

Compile and run $ gcc -Wall -o sum sum.c $ sum Sum is 55

The while statement has the form: while ( condition ) statement The while keeps executing its (compound) statement until its condition becomes false Deciding on a loop condition can be very difficult

Flow Chart for while condition true statement false code after while-loop

Square Root Example /* find square root of n using Newton Raphson method */ #include <stdio.h> int main() { float n, x0, eps = 0.000001; printf("Enter number\n"); scanf("%f", &n); x0 = n; while ( abs(x0*x0 - n)/n > eps) x0 = (x0 + n/x0)/2; printf("Square Root is %f\n", x0); return 0; }

4. Grades Average Example 4.1. The Problem Statement 4.2. How to Start Writing a Program 4.3. Dissect the Problem Statement 4.4. Flesh out the Skeleton 4.5. Consider the Loop 4.6. What is an Average? 4.7. The Final Code: average.c

4.1. The Problem Statement Sec. 3.9 Develop a class averaging program that will process an arbitrary number of grades each time the program is run.

4.2. How to Start Writing a Program Program = Algorithm + Data Structures Algorithm: a series of functions, each using a mix of sequencing, branches, loops, recursion and other functions Data Structures: they reflect the structure of the data in the Problem Statement e.g int, float, arrays, etc

Consider the input/output requirements Dissect (‘Pull apart’) the Problem Statement Use top-down design (also called stepwise refinement)

4.3. Dissect the Problem Statement The inputs are the grades The output is the average Use a loop to read in ‘an arbitrary number of grades’

4.4. Flesh Out the Skeleton /* grades.c */ #include <stdio.h> int main() { /* declare the variables */ float average; /* calculate class average using a loop to read in the grades */ printf("Class average is %f\n", average); return 0; }

4.5. Consider the Loop The big problem: while ( condition?? ) { printf("Enter grade:"); scanf("%d", &grade); /* calculate the on-going average using grade */ } The big problem: what is the loop condition?

The Loop with a Condition printf("Enter grade, -1 to end: "); scanf("%d", &grade); while (grade != -1) { /* calculate the on-going average using grade */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); }

The Skeleton with the Loop /* grades.c */ #include <stdio.h> int main() { /* declare the variables */ float average; int grade; printf("Enter grade, -1 to end: "); scanf("%d", &grade); : continued

while (grade. = -1) { /. calculate the on-going average using grade while (grade != -1) { /* calculate the on-going average using grade */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); } printf("Class average is %f\n",average); return 0; }

4.6. What is an Average? average = total of grades / number of grades Use two new variables: total counter

4.7. The Final Code: average.c Sec. 3.9 /* Class Average Program */ #include <stdio.h> int main() { float average; int counter, grade, total; /* initialization phase */ total = 0; counter = 0; : continued

/* looping phase */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); while(grade != -1) { total = total + grade; counter = counter + 1; printf("Enter grade, -1 to end: "); scanf("%d", &grade); } : : continued

/. termination phase. / average = (float) total / counter; / /* termination phase */ average = (float) total / counter; /* can you see a bug ? */ printf("Class average is %.2f", average); return 0; }

Compile and run $ gcc -Wall -o average average.c $ average Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 6 Enter grade, -1 to end: -1 Class average is 58.33

5. Incrementing and Decrementing Add 1 to c by writing: c = c + 1; Also: c += 1; Also: c++; Also: ++c;

Fig. 3.13 /* Preincrementing and postincrementing */ #include <stdio.h> int main() { int c; c = 5; printf("%d\n", c); printf("%d\n",c++); /*post-increment*/ printf("%d\n\n", c); : continued

c = 5; printf("%d\n", c); printf("%d\n",++c); /. pre-increment c = 5; printf("%d\n", c); printf("%d\n",++c); /*pre-increment*/ printf("%d\n", c); return 0; }

Output: 5 5 6 5 6 6

5.2. Decrementing Take 1 from c by writing: Also: c -= 1; Also: c--; c = c - 1; Also: c -= 1; Also: c--; Also: --c;

6. Counter-controlled Repetition Fig. 4.1. /* Counter-controlled repetition */ #include <stdio.h> int main() { int counter = 1; while (counter <= 10) { printf ("%d\n", counter); ++counter; } return 0; }

Output 1 2 3 : 10

/. Counter-controlled repetition. / #include <stdio /* Counter-controlled repetition */ #include <stdio.h> int main() { int counter = 0; while (++counter <= 10) printf ("%d\n", counter); return 0; }

7. The for Statement 7.1. The Parts of a for 7.2. The for is a sort of while 7.3. Some Examples 7.4. Summation 7.5. Compound Interest

7.1. The Parts of a for Sec. 4.4 #include <stdio.h> int main() { int cnt; for (cnt = 1; cnt <= 10; cnt++) printf("%d\n", cnt); return 0; } the increment occurs after the loop body has been executed test for continuing initial value final value increment

Flow Chart for for-loop initial value test for continuing true body (e.g. printf) increment false code after for-loop

7.2. The for is a sort of while for (expr1; expr2; expr3) statement; is equivalent to: expr1; while (expr2) { statement; expr3; }

7.3. Some Examples for(i = 7; i <=77; i += 7) statement;

x =2; y = 10; for(j = x; j <= 4*x*y; j += y/x) statement; equivalent to: for(j = 2; j <= 80; j += 5) statement;

for(j = 10; j > 20; j++) statement; equivalent to: j = 10;

7.4. Summation fig. 4.5 /* Summation using a for-loop */ #include <stdio.h> int main() { int sum = 0, num; for (num = 2; num <= 100; num += 2) sum += num; printf("Sum is %d", sum); return 0; }

7.5. Compound Interest Fig. 4.6 Amount = principal * (1 + rate)year

/. Calculating compound interest for 10 years. / #include <stdio /* Calculating compound interest for 10 years */ #include <stdio.h> #include <math.h> int main() { int year; double amount, principal = 1000.0, rate = 0.05; printf("%4s%21s\n", "Year", "Amount on deposit"); : continued

for (year = 1; year <= 10; year++) { amount = principal for (year = 1; year <= 10; year++) { amount = principal * pow(1 + rate, year); printf("%4d%10.2f\n", year, amount); } return 0; }

Some Points On p.864 of D&D: Also look at math.h in /usr/include pow()'s arguments should be doubles,: if they are integer or float then they are cast into doubles (e.g. year). On p.864 of D&D: double pow(double x, double y); Also look at math.h in /usr/include

Compile and run % gcc -Wall -o compound compound.c % compound Year Amount on deposit 1 1050.00 2 1102.50 : : 10 1628.89

Explicit Libraries But on some machines: Must type: % gcc -Wall -o compound compound.c ld: undefined: pow Must type: % gcc -Wall -o compound compound.c -lm

8. The switch Statement 8.1. The Parts of a switch 8.2. Counting Letter Grades

8.1. The Parts of a switch For multiple choices: condition c1 c2 c3 task-A task-B task-C

switch (condtion) { case c1 : task-A; break; case c2 : task-B; break; case c3 : task-C; break; : }

8.2. Counting Letter Grades Fig. 4.7 /* Counting letter grades */ #include <stdio.h> int main() { int grade; int acount = 0, bcount = 0, ccount = 0, dcount = 0, fcount = 0; printf("Enter the letter grades.\n"); printf("Enter EOF to end.\n"); : continued

while ((grade = getchar()) while ((grade = getchar()) != EOF) { switch (grade) { case 'A': case 'a': ++acount; break; case 'B': case 'b': ++bcount; break; case 'C': case 'c': ++ccount; break; case 'D': case 'd': ++dcount; break; : : continued

case 'F': case 'f': ++fcount; break; case '\n': case' ': break; default: printf("Incorrect letter grade entered."); printf(" Enter a new grade.\n"); break; } } : : important continued

printf("\nThe totals for each printf("\nThe totals for each letter grade are:\n"); printf("A: %d\n", acount); printf("B: %d\n", bcount); printf("C: %d\n", ccount); printf("D: %d\n", dcount); printf("F: %d\n", fcount); return 0; }

Some Points Very common coding style: while((grade = getchar()) != EOF) { : } getchar() reads the next character as an integer and assigns it to grade EOF is an integer constant representing the end-of-file value. Defined in stdio.h

The line includes the newline character (represented by '\n') getchar() will only start reading a line of characters when it has been terminated with a return or EOF. The line includes the newline character (represented by '\n')

Output from letter grades program Enter the letter grades. Enter EOF to end input. A B C C A X Incorrect letter grade entered. Enter a new grade. D : I typed return and <ctrl>D continued

Totals for each letter grade were: A: 2 B: 1 C: 2 D: 1

9. The break Statement Sec. 4.9 Causes execution to jump to the next statement after the loop (or switch) containing the break. while(1) { scanf("%lf", &x); if (x < 0.0) break; printf("%f\n", sqrt(x)); } /* break jumps to here */ :

10. More Complex Input If you want to read several values from a line, then use scanf(), and check its return value. scanf() returns the number of values it has read in. Example: assume each line contains two integers and a float: 2 3 12.6 5 1 9.2 13 23 17.56

Code Fragment int d1, d2; float f; : while (scanf(“%d %d %f”, &d1, &d2, &f) == 3) /* do something with input values */ :

Note The spaces between the numbers (including tabs and newlines) are ignored by scanf() when it is looking for things to read in. e.g. could write: 2 3 12.6 5 1 9.2 13 23 17.56