ECET 264 C Programming Language with Applications. C Program Control

Similar documents
ECET 264 C Programming Language with Applications

بسم اهلل الرمحن الرحيم

Chapter 4 C Program Control

ECET 264 C Programming Language with Applications

Computers Programming Course 7. Iulian Năstac

Lecture 9 - C Functions

Loop Controls, Decision Making, Functions, and Data Array Processing

Chapter 4 C Program Control

Lecture 3. More About C

Dept. of CSE, IIT KGP

Chapter 3 Structured Program Development

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

C: How to Program. Week /Apr/23

Fundamentals of Programming Session 8

Programming for Engineers Iteration

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Decision Making and Loops

COMP 208 Computers in Engineering

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

C Functions. 5.2 Program Modules in C

Chapter 2 - Introduction to C Programming

LAB 5: REPETITION STRUCTURE(LOOP)

Chapter 2 - Control Structures

A Look Back at Arithmetic Operators: the Increment and Decrement

C: How to Program. Week /Mar/05

n Group of statements that are executed repeatedly while some condition remains true

C++ Programming Applied to Robotics, Mark Aull Lesson 2: Intro to Visual Studio, debugger Intro to C++, variables, conditionals, loops, strings

Introduction to C Language

BSM540 Basics of C Language

Tail recursion. Decision. Assignment. Iteration

Lecture 04 FUNCTIONS AND ARRAYS

CS110D: PROGRAMMING LANGUAGE I

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

LAB 5: REPETITION STRUCTURE(LOOP)

Module 4: Decision-making and forming loops

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Structured Programming. Dr. Mohamed Khedr Lecture 9

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

C: How to Program. Week /Apr/16

AMCAT Automata Coding Sample Questions And Answers

Fundamentals of Computer Science. Sentinel Based Repetition

Strings. Daily Puzzle

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Technical Questions. Q 1) What are the key features in C programming language?

Chapter 2 - Control Structures

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Decision Making -Branching. Class Incharge: S. Sasirekha

ECET 264 C Programming Language with Applications

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath


CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Structured Program Development

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Functions. Systems Programming Concepts

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Two Dimensional Array - An array with a multiple indexs.

3 The L oop Control Structure

Repetition and Loop Statements Chapter 5

CS1100 Introduction to Programming

Control Structure: Loop

Beginning C Programming for Engineers

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Flow Control. CSC215 Lecture

Dr. R. Z. Khan, Associate Professor, Department of Computer Science

Lecture 6. Statements

Prepared by: Shraddha Modi

Subject: PIC Chapter 2.

Two Dimensional Array - An array with a multiple indexs.

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

Computer System and programming in C

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Structured Program Development in C

EL2310 Scientific Programming

Chapter 2 - Control Structures

C Programming Language

C Program Development and Debugging under Unix SEEM 3460

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

Conditional Statement

Transcription:

ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 7 - Paul I. Lin 1 Lecture 7 C Program Controls Common Programming Errors: Syntax Errors, Logic Errors, Run-time Errors, and Undetected Errors C Program Control Structures Repetition Statements For Statement Do While Repetition Statement Selection Statements Switch multiple selection statement Break Continue Lecture 7 - Paul I. Lin 2 1

Lecture 7 C Program Controls C Programming Examples Example 7-1: Interest Calculation Example 7-2: ASCII Number Generation Example 7-3: Read Keyboard Inputs and Echo them on to the Monitor Screen Example 7-4: Generating 10 Random Numbers Example 7-5: Generating Seeded and Unseeded Random Numbers Example 7-6: Counting the Number of a, b, and c characters in a text file Example 7-7: A Calculator Program Lecture 7 - Paul I. Lin 3 Common Programming Errors Syntax errors Grammatical errors, such as misspelling or incorrect punctuation Can be caught by the compiler Logic errors (Caused as a result of faulty program design) Program logical errors Misuse operators, such as ==, = Program does not terminate properly or an endless loop Errors caused by inappropriate end of data Run-time errors (Errors occur during the execution of a program) Other undetected errors (Fail to perform its intended task; incorrect results) Lecture 7 - Paul I. Lin 4 2

Repetition Essentials Repetition is a group of statements the computer executes repeatedly while the condition remains true Counter Controlled repetition (definite repetition) A control variable (or loop counter) A proper initial value for the control variable The increment (or decrement) by which the control variable is modified each time through the loop Testing final value of the control variable to know when to end the loop Lecture 7 - Paul I. Lin 5 Repetition Essentials (cont.) Sentinel Controlled repetition (indefinite repetition) The precise number of repetitions is not known in advance The loop includes statement(s) that obtain ending condition data each time the loop is performed The ending condition is determined through a distinct input data called sentinel value which indicates end of data Lecture 7 - Paul I. Lin 6 3

Repetition Structures A loop is a form of repetition in which a sequence of statements is repeated a number of times. Repetition structures: are to take actions until the condition fails. while for do while Lecture 7 - Paul I. Lin 7 while Loop Repetition Structures (cont.) Control variables used in the loop control testing must be initialized Testing for the termination condition is done at the top of the while() loop while (1) endless loop which is equivalent to #define true 1 while(true). or for ( ; ; ). Lecture 7 - Paul I. Lin 8 4

for Loop for statement is a repetition statement provides a leading-test construct with initialization and re-initialization provisions for loop allows to repeat the statements for a fixed number of times Basic Format: for(initialization; end_cond_checking; update) s1; s2; sn; Lecture 7 - Paul I. Lin 9 for Loop (cont.) Form 1: Null Statement (can be used as a short time delay routine) for (i = 0; i< 10; i++) ; Form 2: Simple Statement for (i = 0; i < 10; i++) sum += 1; i =0 NO statement to be executed Loop continuation condition 10 is a final value of control variable ONE statement to be executed i< 10? False True sum += 1 i ++ Lecture 7 - Paul I. Lin 10 5

for Loop (cont.) Form 3: Compound Statement for (init; end_cond_checking; update) s1; s2; Form 4: Nested for Loops for ( ; ;) /* End Less Loop */ for (init; end_cond_checkig; update) s1; s2; s3; for (init; end_cond_checking; update) s4; More than ONE statement to be executed Include more then one FOR statement to be executed Lecture 7 - Paul I. Lin 11 Example 7 1 Interest Calculation This C program computes compound interest using the FOR loop. A person invests $500.00 in a saving account yielding 3% of interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years using the following equation: a = p(1+r) n where p is the original amount invested r is the annual interest rate n is the number of year a is the amount on deposit at the end of the nth year Lecture 7 - Paul I. Lin 12 6

Example 7 1 (cont.) Interest Calculation /* Calculating compound interest*/ #include <stdio.h> #include <math.h> /* function main begins program execution */ int main() double amount; /* amount on deposit */ double principal = 500.0; /* starting principal */ double rate = 0.03; /* annual interest rate */ int year; /* year counter */ /* output table column head */ printf( "%4s%21s\n", "Year", "Amount on deposit" ); Lecture 7 - Paul I. Lin 13 Example 7 1 (cont.) Interest Calculation /* calculate amount on deposit for each of ten years */ for ( year = 1; year <= 10; year++ ) /* calculate new amount for specified year */ amount = principal * pow( 1.0 + rate, year ); /* output one table row */ printf( "%4d%21.2f\n", year, amount ); /* end for */ return 0; /* indicate program ended successfully */ Lecture 7 - Paul I. Lin 14 7

Example 7 1 (cont.) Interest Calculation Lecture 7 - Paul I. Lin 15 Example 7 2 ASCII Number Generation Write a C program to generate ASCII numbers (0 to 9) and display them as both decimal and hex number on the screen: %c -- the format specified reserves a default length of spaces for printing a character %d -- the format specified reserves a default length of spaces for printing a decimal number %x -- the format specified reserves a default length of spaces for printing a hex number Lecture 7 - Paul I. Lin 16 8

Example 7 2 (cont.) ASCII Number Generation #include <stdio.h> void main() char ascii; for (ascii = '0'; ascii <= '9'; ascii++) printf("ascii %c = Decimal %d = Hex %x \n", ascii, ascii, ascii); Lecture 7 - Paul I. Lin 17 Example 7 2 (cont.) ASCII Number Generation Output: ASCII 0 = Decimal 48 = Hex 30 ASCII 1 = Decimal 49 = Hex 31 ASCII 2 = Decimal 50 = Hex 32 ASCII 3 = Decimal 51 = Hex 33 ASCII 4 = Decimal 52 = Hex 34 ASCII 5 = Decimal 53 = Hex 35 ASCII 6 = Decimal 54 = Hex 36 ASCII 7 = Decimal 55 = Hex 37 ASCII 8 = Decimal 56 = Hex 38 ASCII 9 = Decimal 57 = Hex 39 Lecture 7 - Paul I. Lin 18 9

Example 7 3: Read Keyboard Input and Echo them on to Monitor Screen /* char0.c A simple for loop for controlling the activities of the keyboard input and screen output. */ #include <stdio.h> #define NEWLINE '\n' void main() char name[30]; int c; /*Execute following forever, CTRL C to stop*/ for(;;) printf("\nplease enter your name: "); gets(name); puts("is this your name?"); puts(name); printf("\nplease enter a digit: "); c = getchar(); puts("\nis this the digit?"); putchar(c); putchar(newline); fflush(stdin); /* Flush the keyboard buffer */ /* end of char0.c */ Lecture 7 - Paul I. Lin 19 Example 7 3: Read Keyboard Input and Echo them on Monitor Screen (cont.) Output: Please enter your name: Paul Lin Is this your name? Paul Lin Please enter a digit:2 Is this the digit? 2 Please enter your name: You entered Lecture 7 - Paul I. Lin 20 10

Example 7 4 Generating 10 Random Numbers /* This program seeds the random-number generator with the time, then displays 10 random integers */ #include <stdlib.h> #include <stdio.h> #include <time.h> int main( void ) int i; /* Seed the random-number generator with current time so that the numbers will be different every time we run the program. */ srand( (unsigned)time( NULL ) ); /* Display 10 numbers. */ for( i = 0; i < 10; i++ ) printf( " %6d\n", rand() ); Lecture 7 - Paul I. Lin 21 Example 7 4 (cont.) Generating 10 Random Numbers Sample Output: 19430 28222 9710 12070 7513 9501 1767 26041 11872 4097 Lecture 7 - Paul I. Lin 22 11

Example 7 5: Generating Seeded and Unseeded Random Numbers /* randgen.c - Generating seeded and unseeded pseudo random numbers */ #include <stdio.h> #include <math.h> #include <stdlib.h> void main(void) int n; /* Generate 4 unseeded pseudo random numbers*/ for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Generate time() function seeded peudo random numbers */ srand((unsigned)time(null)); Lecture 7 - Paul I. Lin 23 Example 7 5: Generating Seeded and Unseeded Random Numbers (cont.) for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Reset peudo random generator */ srand(1); for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); Lecture 7 - Paul I. Lin 24 12

Example 7 5: Generating Seeded and Unseeded Random Numbers (cont.) Lecture 7 - Paul I. Lin 25 Example 7 6: Counting the Number of a, b, and c Characters /* if0.c - Counting A, B, C characters */ #include <stdio.h> #define SIZE 81 #define FORMAT "A = %d, B = %d, C = %d\n" void main() int i; int a, b, c; // counters char ch, s[size]; a = b = c = 0; Lecture 7 - Paul I. Lin 26 13

Example 7 6: Counting the Number of a, b, and c Characters (cont.) for(;;) // Run forever; Enter <Ctrl C> to exit puts("enter a string"); gets(s); for(i = 0; (ch = s[i])!= '\0'; i++) if((ch == 'A') (ch == 'a')) a++; if((ch == 'B') (ch == 'b')) b++; if((ch == 'C') (ch == 'c')) c++; printf(format, a, b, c); Lecture 7 - Paul I. Lin 27 Example 7 6: Counting the Number of a, b, and c Characters (cont.) Output: You entered Enter a string The C Programming Language A = 3, B = 0, C = 1 Enter a string Lecture 7 - Paul I. Lin 28 14

do while while loop tests for the termination condition at the top of the while() loop before the body of the loop performed do while loop always executes its loop body at least once before testing the termination conditions do while loop is good to perform counting, adding, searching, sorting, monitoring, etc Lecture 7 - Paul I. Lin 29 do while (cont.) Syntax: Form 1: Simple Statement do statement; while (condition); Form 2: Compound Statements do s1; s2; s3; while (condition); Lecture 7 - Paul I. Lin 30 15

do while (cont.) Using Relational and Logical operators for Checking Ending Condition: do.. while(1) /* Endless loop */ do.. while(a > b) /* a greater than b */ do.. while(a <= b) /* a less or greater than b */ do.. while(a!= b) /* a not eaual to b */ do.. while(a == b) /* a equal to b */ do.. while(a < (c + b)) /* a less than c + b */ do.. while(!a) /* while not a */ do.. while(a && b) /* while a and b are both nonzero or true */ do.. while(a b) /* while either a or b is nonzero or true */ Lecture 7 - Paul I. Lin 31 switch A multiple selection statement Consists of a series of case labels, and optional default case Multi-way branch (a chain of if-else statement) To select among several different cases break is used to end each case to exit the switch The default case is optional Lecture 7 - Paul I. Lin 32 16

switch (cont.) General form of switch(n) Syntax: switch (n) case 1: statement 1; break; case n: statement n; break; default: statement; where n can only be an integer, unsigned integer, or character type variable Lecture 7 - Paul I. Lin 33 switch (cont.) Example: int j = 3; switch(j) case 1: printf( case 1 \n ); break; case 2: printf( case2 \n ); break; default: printf( case others \n ); break; Lecture 7 - Paul I. Lin 34 17

Example 7 7 A Calculator Program Problem Statement You are asked to write a C program that can be used as a calculator program. The requirement of this program is as follows: It will run under a DOS virtual machine using text based user interface. It will prompt the user to enter two numbers It then asks for one of the calculation: addition, subtraction, multiplication, or division The program calculates the result Displays answer and repeats the same calculation Analysis Three variables are required switch, case, multi-decision making is preferred Endless loop, Ctrl C to exit the loop Lecture 7 - Paul I. Lin 35 Example 7 7 A Calculator Program (cont.) /* switch0.c */ #include <stdio.h> #include <stdlib.h> void main() float n1, n2, result; char op[2]; while(1) /* Enter <Ctrl C> to exit */ fflush(stdin); puts("hit any key to continue, Ctrl C to exit\n"); getchar(); /* waiting for user to input */ printf("\nenter a number: "); scanf( %f, &n1); /* Console input */ printf("\nenter second number: "); scanf( %f, &n2); /* Console input */ Lecture 7 - Paul I. Lin 36 18

Example 7 7 A Calculator Program (cont.) printf("\nselect an operator +,-,*, x, / or \\: "); scanf( %s, op); switch(op[0]) case '+': result = n1 + n2; printf("%f\n", result); break; case '-': result = n1 - n2; printf("%f\n", result); break; case '*': case 'x': case 'X': result = n1 * n2; printf("%f\n", result); break; case '/': case '\\': result = n1 / n2; printf("%f\n", result); break; default: puts("wrong operator entered"); Lecture 7 - Paul I. Lin 37 Example 7 7 A Calculator Program (cont.) Output: Hit any key to continue Enter a number: 12.0 Enter second number: 20.0 Select an operator +,-,*, x, / or \: * 240.000000 Hit any key to continue Lecture 7 - Paul I. Lin 38 19

Summary Common Program Errors C Program Control More Repetition Statements For Statement Do While Repetition Statement More Selection Statements Switch multiple selection statement Next - Break and Continue statement Equality operator (==) and assignment operator (=) Lecture 7 - Paul I. Lin 39 Question? Answers lin@ipfw.edu Lecture 7 - Paul I. Lin 40 20