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

Slides:



Advertisements
Similar presentations
Control Structures.
Advertisements

Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Pemrograman Dasar Control Flow Statements: Decision Making or Selection PTIIK - UB 1.
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
Chapter 6 Control Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
The switch statement: an N-way selection statement.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Computer programming Lecture 4. Lecture 4: Outline Making Decisions [chap 6 – Kochan] –The if Statement –The if-else Construct –Logical Operators –Boolean.
1 4.8The do/while Repetition Structure The do/while repetition structure –Similar to the while structure –Condition for repetition tested after the body.
C Program Control Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Program Looping Making Decisions Copyright © 2012 by Yong-Gu Lee
IF-ELSE IF-ELSE STATEMENT SWITCH-CASE STATEMENT Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Lecture-2 Operators and Conditionals. Variables(again???) Type: Representation of “bits” in memory Variables: Name for a memory object. Starts with letters,
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
A First C Program /* Print a Message */ #include main() { printf("This is a test!\n"); } The program is compiled and run as cc pg32.c  a.out  This is.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Previously Repetition Structures While, Do-While, For.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Copyright 2003 Scott/Jones Publishing Making Decisions.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
2011 Calendar Important Dates/Events/Homework. SunSatFriThursWedTuesMon January
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
COMP Loop Statements Yi Hong May 21, 2015.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
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.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Making Decisions in c. 1.if statement Imagine that you could translate a statement such as “If it is not raining, then I will go swimming” into the C.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
Chapter 4 – C Program Control
The if…else Selection Statement
Java Language Basics.
Control Structures and Data Files
Decisions Chapter 4.
Chapter 4: Making Decisions.
The if Statement Format or No Condition satisfied? Yes
Week 4 – Repetition Structures / Loops
Chapter 4: Making Decisions.
Flow of Control.
Flow of Control.
Starting JavaProgramming
- Additional C Statements
Flow of Control.
Program Control Topics While loop For loop Switch statement
CprE 185: Intro to Problem Solving (using C)
Dale Roberts, Lecturer IUPUI
Chapter 4 - Program Control
2015 January February March April May June July August September
Presentation transcript:

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

The if Statement Format if ( condition ) program statement; or if ( condition ) { program statements; } Flow Condition true? Program statements Yes No

Example Calculating the absolute value of an integer number < 0 number = - number; Yes No printf(“type in your number: “); scanf(“%i”, &number); if ( number < 0 ) number = -number; printf(“\nThe absolute value is %i\n”, number);

The if-else Statement Format if ( condition ) program statement 1; else program statement 2; Flow condition true? program statement 1 Yes No program statement 2

The else if Statement Format if ( condition1 ) program statement 1; else if (condition2) program statement 2; Flow condition1 true? program statement 1 Yes No condition2 true? No program statement 2 Yes

One example if (condition1) program statement 1; else if (condition2) program statement 2; else program statement 3; condition1 true? program statement 1 Yes No condition2 true? No program statement 3 program statement 2 Yes

Boolean Variables Declaration –Boolean variables are represented by integers Value –0 represents false –1 representing true, mostly Any nonzero value represents true in C

Logical Operators Why –Make a decision based on multiple conditions What are they OperatorExampleDescription ||x widthlogical OR &&x >= 0 && x <= widthlogical AND !!(x < 0)logical NOT

Logical OR Returns false only if both expressions are false Example: for (i=5 ; i<=95; i+=5) { if((i 60)) { printf(“%i”, i); } ABA || B True FalseTrue FalseTrue False

Logical AND Returns true only if both expressions are true Example: for (i=5 ; i<=95; i+=5) { if((i > 35) && (i < 60)) { printf(“%i”, i); } ABA && B True False TrueFalse

Logical NOT Inverts the Boolean value of an expression Example: int a = 0; if (!a) { printf(“a is not 0\n”); } a = 1; if (a) { printf(“a is 1\n”); } A!A TrueFalse True

Conditional Expressions Relational expression using ==, !=, >, >=, <, <= –The value of “relational expression” is 1 if the relation is true, and 0 if false. Operators can be combined with logical operators (with decreasing precedence): –! (NOT) –&& (AND) –|| (OR) Rules: –&& and || are evaluated left to right Example: c==' ' || c=='\t' || c=='\n'

Example: Giving Final Grade A(100-90), B(89-80),C(79-70),D(69-60),F(59-0) if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;

Evaluate a simple expression Objective: –Evaluate expression and display results with input in the form: number operator number Example –User input: –Program output: 15

Program #include int main(void) { float v1, v2; char operator; printf("Type in your expression: \n"); scanf("%f %c %f", &v1, &operator, &v2); if ( operator == '+' ) printf("%.2f\n", v1 + v2); else if ( operator == '-' ) printf("%.2f\n", v1 - v2); else if ( operator == '*' ) printf("%.2f\n", v1 * v2); else if ( operator == '/' ) printf("%.2f\n", v1 / v2); return 0; } Need to check v2 == 0?

Corrections Change else if ( operator == '/' ) printf("%.2f\n", v1 / v2); to else if ( operator == '/' ) if ( v2 == 0 ) printf(“Division by zero.\n”); else printf("%.2f\n", v1 / v2);

Watch Out for This!!! The assignment operator “=“ and the equality operator “==“ ARE VERY DIFFERENT, DO NOT CONFUSE THEM! This code compiles and runs, but does not do what you may expect: if (x = 0) { x = 1; } printf(“x = %i\n,x);

How to get out of a loop prematurely? Use the break statement –Skips all subsequent statements in the loop –Exits immediately from the current loop –Continues execution after the loop Or the continue statement –Skip subsequent statements in the current iteration –Continue execution with the next iteration

Example – summation of valid scores int count, n = 10, sum = 0, score; for (count = 0; count < n; count++){ scanf("%d", &score); if (score 100) continue; sum = sum + score; }

Example – summation of valid scores int count, n = 10, sum = 0, score; for (count = 0; count < n, count++) { scanf("%d", &score); if (score 100) { printf(“Bad data. Exiting\n”); break; } sum = sum + score; }

The switch Statement When to use –The value of a variable successively compared against different values Format switch( expression ) { case value 1: program statement 1; break; case value 2: program statement 2; break; ׃ case value n: program statement n; break; default : program statement n+1; break; } == value 1 evaluate expression statement 1 Y N == value 2 == value n N N statement n+1 Y statement 2 Y statement n

Example switch ( operator ) { case '+': printf("%.2f\n", v1 + v2); break; case '-': printf("%.2f\n", v1 - v2); break; case '*': printf("%.2f\n", v1 * v2); break; case '/': if ( v2 == 0 ) printf(“Division by zero.\n”); else printf("%.2f\n", v1 / v2); break; default: printf("Unknown operator!\n"); break; }

Another example switch (month) { case 1: printf("January"); break; case 2:printf("February"); break; case 3: printf("March"); break; case 4: printf("April"); break; case 5:printf("May"); break; case 6:printf("June"); break; case 7:printf("July"); break; case 8:printf("August"); break; case 9:printf("September"); break; case 10:printf("October"); break; case 11:printf("November"); break; case 12:printf("December"); break; default:printf("Invalid month.");break; }

More on switch Statement case value 1: statement 1; case value 2: statement 2; break ; == value 1 statement 1 Y N == value 2 N Y statement 2 Usually, this is a BUG! And one that is often very hard to find! “MISSING BREAK”

The conditional operator Format: condition ? expression1 : expression2 Same as if ( condition ) { expression1; } else { expression2; } Except: the “?” can be used in an expression.