1 Decision Making if (score<40) { printf(“Fail\n”); }else { printf(“Pass\n”); } Not recommended in practice since it does not follow general fashion of.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
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.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 4 Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
Control Statements Spring Semester 2013Programming and Data Structure1.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Structured Programming
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Chapter 5: Structured Programming
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
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
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
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;
Introduction to Loops Iteration Repetition Counting Loops Also known as.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Chapter 7 Problem Solving with Loops
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
CISC105 – General Computer Science Class 4 – 06/14/2006.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
Chapter 5: Structured Programming
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Control Structures Lecture 7.
Looping.
CS1100 Computational Engineering
Structured Program
Chapter 4 - Program Control
3 Control Statements:.
UMBC CMSC 104 – Section 01, Fall 2016
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

1 Decision Making if (score<40) { printf(“Fail\n”); }else { printf(“Pass\n”); } Not recommended in practice since it does not follow general fashion of programming language; other language does not offer this shorthand. Also because only ONE statement is allowed for each condition (not much use practically) Might be useful in understanding other people’s coding /* shorthand version of if else statement */ (score<40) ? printf (“Fail\n”) : printf(“Pass\n”);

2 …. printf(“Game Menu\n”); printf(“1 – Star Craft 2 – Red Alert 3 – War Craft\n”); printf(“Enter your selection:”); scanf(“%d”,&choice); if (choice==1) { /* Lauch Star Craft */ } else { if (choice==2) { /* Lauch Red Alert */ } else { /* Lauch War Craft */ } switch…case Multiple Selection Structure Consider creating a selection menu What if there are 10 options or more? The if…else statement would have to be nested for 10 levels or more. It doesn’t seems like a neat solution, does it?

3 …. printf(“Enter your selection:”); scanf(“%d”,&choice); switch(choice) { case 1: /* Launch Star Craft */ break; case 2: /* Launch Red Alert */ break; case 3: /* Launch War Craft */ break; } switch…case Multiple Selection Structure Let’s see how switch..case statement can help... Isn’t it looks much better?

4 switch…case Multiple Selection Structure Flowchart of the switch structure true false case a case a action(s)break case b case b action(s)break false case z case z action(s)break true default action(s)

5 …. int choice = 0; switch(choice) { case 1: printf(“Launching Star Craft\n”); break; case 2: printf(“Launching Red Alert\n”); break; case 3: printf(“Launching War Craft\n”); break; default: printf(“Invalid Options!\n”); } switch…case Multiple Selection Structure Guess what’s the output of this program…. Output Invalid Options!

6 switch…case Multiple Selection Structure Exercise 1. Create a program that read in an integer from user. The value range from 0 to 9. Next, print out the value in Bahasa Malaysia. Example, if user input 7, the output is ‘Tujuh’. If user input any value not within the range, display message: ‘Jangan nakal-nakal…nanti Sir rotan!’

7 //Exercise Answer #include main() { int number; printf("Please enter a number: "); scanf ("%d", &number); switch(number) { case 0: printf("Sifar"); break; case 1: printf("Satu"); break; case 2: printf("Dua"); break; case 3: printf("Tiga"); break; case 4: printf("Empat"); break; case 5: printf("Lima"); break; case 6: printf("Enam"); break; case 7: printf("Tujuh"); break; case 8: printf("Lapan"); break; case 9: printf("Sembilan"); break; default: printf("Jangan nakal nakal, nanti sir rotan!"); }

8 …. int counter; counter = 0; while (counter<5) { printf(“%d, “,counter); counter = counter + 1; } While Repetition/Loop Structure Guess what’s the output of this program…. Output 0, 1, 2, 3, 4

9 While Repetition/Loop Structure while (loop continuation test) { statement 1 statement 2 …... } //statement to executed after exiting the while loop If the loop continuation test is TRUE, the statements within the braces { } will be executed. When it reach the point right before ‘}’, it will return to the beginning of the loop and repeat the process. if FALSE, exit the loop (go to first statement after ‘}’) true Loop continuation test Statement 1 Statement 2... false WHILE LOOP

10 …. int counter = 1, fact=1, n=4; while (counter<=n) { fact = fact * counter; counter = counter + 1; } printf(“ %d factorial is %d\n”, n, fact); While Repetition/Loop Structure Exercises – What’s the output? Output 4 factorial is 24

11 …. int counter = 0, row=3, col; while (counter<row) { col = 0; while (col<(counter+1)) { printf(“*”); col = col + 1; } printf(“\n”); counter = counter + 1; } While Repetition/Loop Structure Exercises – What’s the output? Output * ** ***

12 …. int counter=0, row=3, counter2, col=4; while (counter<row) { counter2 = 0; while (counter2<col) { printf(“*”); counter2 = counter2 + 1; } printf(“\n”); counter = counter + 1; } While Repetition/Loop Structure Exercises – What’s the output? Output ****

13 …. int counter; counter = 0;//counter initialisation while (counter<5) {//repetition condition checking printf(“%d, “,counter); counter = counter + 1;//counter increment } While Repetition/Loop Structure The earlier examples are typical Counter-controlled repetition structure. Counter-controlled repetition is a definite repetition: number of repetition is known before loop start. while statement is seldom used for this type of repetition; for statement is more popular. (Discuss later) while statement is catered for another type of repetition….

14 …. int score=0; while (score >= 0) { printf(“Enter a score [enter negative score to exit]: “); scanf(“%d”,&score); } While Repetition/Loop Structure Can you tell how many loops there will be? This is a Sentinel-controlled repetition: number of repetition is UNKNOWN. The sentinel value (in this case, a negative score) shall indicate the termination of the loop

15 …. int number, total_digit=0, divider=1; printf(“Please enter a decimal number”); scanf(“%d”, &number); while ((number/divider) != 0) { total_digit=total_digit + 1; divider = divider * 10; } printf(“There are %d digit in %d\n”,total_digit, number); While Repetition/Loop Structure Let’s use it to count the number of digits that form the input integer

16 Ali took a RM100,000 house loan from bank. The interest rate is 8% per annum, compound monthly. The monthly instalment is RM 700. Write a program to find out how long (in years & months) Ali need to fully settle his loan. While Repetition/Loop Structure Another example Can u tell what’s the sentinel value in the above while loop?

17 float balance, monthly_interest, monthly_interest_rate, monthly_instalment; int months = 0; balance = ; monthly_interest_rate = (8.0/100.0)/12.0; while (balance>0.0) { monthly_interest = monthly_interest_rate * balance; balance = balance + monthly_interest - monthly_instalment; months = months + 1; } printf (“%d years %d months\n”, months/12, months%12); While Repetition/Loop Structure

18 While Repetition/Loop Structure Exercises 1.Write a program that reads a positive integer n and then computes and prints the sum of all integers from 1 to n and divisible by 3 2.Write a program that interactively reads test score values until a negative test score is entered and then computes and outputs the average test score. The test score must be validated to ensure that they are between 0 and Write a program that accepts a positive integer and determines whether it is a numerical palindrome (a number that is the same forward and backward, such 13431) [BONUS ]

19 …. int counter; counter = 1; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<4); do...while Repetition/Loop Structure Guess what’s the output of this program…. Output 1, 2, 3,

20 do...while Repetition/Loop Structure do { statement 1 statement 2 …... } (loop continuation test); //statement to executed after exiting the while loop Execute the statements within the braces { }. When it reach the end of the segment, it will perform the loop continuation test. If TRUE, it will return to the beginning of the loop and repeat the process. if FALSE, exit the loop (go to first statement after ‘}’) true Loop continuation test Statement 1 Statement 2... false DO..WHILE LOOP

21 …. int counter; counter = 3; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<1); do...while Repetition/Loop Structure Exercise: What’s the output? Output 3

22 …. int counter; counter = 3; do printf(“%d, “,counter); counter = counter + 1; while (counter<1) do...while Repetition/Loop Structure Exercise: Any syntax error? 1. The braces {} 2. The semicolon ; { } ;

23 counter = 3; do counter = counter + 1 while (counter<1); do...while Repetition/Loop Structure Consider this example... When there is only one statement, it can be written as do statement while (expression); Note that no semicolon is required at the end of statement.

24 int score; printf (“Enter a negative score to exit\n“); do { printf (“Enter a score: “); scanf(“%d”, &score); } while (score>=0); do...while Repetition/Loop Structure Any difference in the output of the programs? int score; printf (“Enter a negative score to exit\n“); while (score>=0) { printf (“Enter a score: “); scanf(“%d”, &score); } do…while will go into the loop at least once while might not go into the loop at all.

25 int i; for (i=0; i<5; i=i+1) { printf(“%d, “,i); } for Repetition/Loop Structure Guess what’s the output of this program…. Output 1, 2, 3, 4, int i; i = 0; while (i<5) { printf(“%d, “,i); i = i + 1; } Exactly the same as this program except on the way of writing it only

26 for Repetition/Loop Structure for (initializations; loop continuation test; counter modifications) { block of statements } //statement to executed after exiting the for loop 1. Perform the initializations (if any) 2. Perform loop continuation test. (if any) 3. If FALSE, exit the loop (go to first statement after ‘}’). 4. If TRUE, the statements within the braces { } will be executed. 5. When it reach the point right before ‘}’, it will return to the beginning of the loop, perform counter modification (if any) 6. Repeat step 2.

27 int i; for (i=4; i>0; i=i-1) { printf(“%d, ”, i); } for Repetition/Loop Structure Exercise: What’s the output? Output 4, 3, 2, 1 int row, col; for (row=0; row>2; row=row+1) { for (col=0; col>3; col=col+1) { printf(“*”); } printf(“\n”); } Output * ** *** Nested for structure

28 for Repetition/Loop Structure Exercise: Any syntax errors? int i; for (i=4 i>0 i=i-1;) { printf(“%d, ”, i); } 1. Missing semicolon ; 2. No semicolon at the end of counter modification Anything wrong with this program logically? int i; for (i=4 i>0 i=i+1;) { printf(“%d, ”, i); } Infinite loop (System Hang) This is called Run-time error. The program will still run except that the result is something undesired Hence, You Must Learn How To Debug Your Program!

29 Exercises 1.Ah Beng save RM500 in his bank account every year and the bank pay him interest of 4% per annum on daily compound basis. Write a program that will calculate the balance of his account at a specific period of saving in year basis. Use for loop to solve this problem. 2. Write a program that can take in a series of number of any length specified by user and find out the smallest and the largest number in the series. Use for loop to solve this problem.

30 Exercises 3. Write a program that prints the following diamond shape. You may use printf statements that print either a single asterisk (*) or a single space. Maximize you use of repetition (with nested for structures) and minimize the number of printf statement. * *** ***** *** *

31 Exercises Answers //No. 1 #include main() { int number_of_year, counter_year, counter_day; double daily_interest, balance; printf("Enter the number of years: "); scanf("%d", &number_of_year); balance = 0; counter_year = 0; for (counter_year=0; counter_year<number_of_year; counter_year++) { balance = balance + 500; for (counter_day = 0; counter_day<365; counter_day++) { daily_interest = balance * (0.04/365); balance = balance + daily_interest; } printf("The balance after %d years is $%.2lf\n", number_of_year, balance); }

32 Exercises Answers //No. 2 #include main() { int series_length, number, min, max, counter; printf("Enter the length of the series: "); scanf("%d", &series_length); counter = 1; printf("Enter number no.%d: ", counter); scanf("%d", &number); max = number; min = number; for (counter=2; counter<=series_length; counter++) { printf("Enter number no.%d: ", counter); scanf("%d", &number); if (min>number) { min = number; } if (max<number) { max = number; } printf("The minimum is %d and the maximum is %d\n", min, max); }

33 Exercises Answers //No. 3 include main() { int cnt_space, cnt_ast, cnt_row; for (cnt_row=1; cnt_row<=3; cnt_row++) { for (cnt_space=1; cnt_space<=3-cnt_row; cnt_space++) { printf(" "); } for (cnt_ast=1; cnt_ast<=cnt_row; cnt_ast++) { printf("*"); } for (cnt_ast=cnt_row-1; cnt_ast>=1; cnt_ast--) { printf("*"); } printf("\n"); } for (cnt_row=2; cnt_row>=1; cnt_row--) { for (cnt_space=1; cnt_space<=3-cnt_row; cnt_space++) { printf(" "); } for (cnt_ast=1; cnt_ast<=cnt_row; cnt_ast++) { printf("*"); } for (cnt_ast=cnt_row-1; cnt_ast>=1; cnt_ast--) { printf("*"); } printf("\n"); }