CPS125 Week 5.

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Week 3 – Selection Structures UniMAP SemPGT C PROGRAMMING1.
Conditional Statement
1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Previously Repetition Structures While, Do-While, For.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
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.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
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.
Problems Reads a letter grade from user and displays the corresponding range for that letter grade (A  , B  80-89, C  70-79, D  60-69, otherwise.
Week 4 Program Control Structure
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Decision Making in C.
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
INC 161 , CPE 100 Computer Programming
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
Chapter 4: Making Decisions.
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Week 3 C Program Structures (Selection Structures)
ECE Application Programming
Chapter 4 (Conditional Statements)
Week 3 – Selection Structures
Condition Statements.
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Introduction to Programming
C Programming Variables.
Chapter 5 Decision Making and Branching
Chapter 7 Conditional Statements
Program Control Topics While loop For loop Switch statement
Week 3 – Program Control Structure
EECE.2160 ECE Application Programming
Selection Control Structure
EECE.2160 ECE Application Programming
Switch Case Structures
Chapter 13 Control Structures
Presentation transcript:

CPS125 Week 5

Practice! /* PROGRAM #9*/ /* PROGRAM TO CALCULATE COURSE MARKS */ #include <stdio.h> #define MidTermWeight 0.30 #define ExamWeight 0.50 #define LabWeight 0.20 main( ){ float MidTerm, Exam, Lab; float WrittenWork, LabWork, Grade; /* Input the mid-term, exam and lab mark */ printf("Please enter your mid-term mark: "); scanf("%f", &MidTerm); printf("Please enter your exam mark: "); scanf("%f", &Exam); printf("Please enter your lab mark: "); scanf("%f", &Lab); /* Calculate the grade, test if the grade is A+ and print the result */ WrittenWork = MidTerm * MidTermWeight + Exam * ExamWeight; LabWork = Lab * LabWeight; Grade = WrittenWork + LabWork; if (Grade >= 90) printf("Definitely A+.\n"); else printf("Either B or C or D or even F!.\n");}

Nested if … else Very similar to if … else … statement seen before Example: if (exp_1) stat_1; else if (exp_2) stat_2; stat_3; Description: If exp_1 is TRUE then stat_1 If exp_1 is FLASE and exp_2 is TRUE then stat_2 If exp_1 is FLASE and exp_2 is FALSE then stat_3

Practice!/* PROGRAM #10 */ /* PROGRAM TO CALCULATE GST AND PST */ #include <stdio.h> #include <stdlib.h> #define GST 0.08 #define PST 0.05 main( ){ char choice; float Ptax, Gtax; float BTprice, ATprice; /* Get the selected letter by user */ printf("Use the menu - Select a Letter:\n"); printf("P] Provincial Tax. G] Goods &Services Tax.\n"); printf("Your selection (P or G): "); scanf("%c", &choice); /* Get the price before tax, calculate GST and PST print the result*/ printf("Please enter the Before the Tax price"); scanf("%f", &BTprice);

PrACTICE! Program: CALCULATE GST AND PST if (choice == ‘G’){ ATprice = GST * BTprice; printf("The Before Tax Price is %f.\n",BTprice); printf("The After Tax Price is %f.\n”, ATprice); } else if (choice == ‘P’){ ATprice = PST * BTprice; } else{ printf("That was not one of the choices.\n"); printf("Sorry!\n"); } exit(0); }

Practice more! /* PROGRAM #11 */ /* PROGRAM TO CALCULATE COURSE GRADE*/ #include <stdio.h> main( ){ float Grade; /* Input the grade */ printf("Pls enter your grade in CMTH140: "); scanf("%f", &Grade); /* Calculate the grade and print the result*/ if ((Grade <= 100) && (Grade >= 90)) printf("Congratulations! A+ grade.\n"); if ((Grade <= 89) && (Grade >= 85)) printf("Excellent! A grade.\n"); if ((Grade <= 84) && (Grade >= 80)) printf("Excellent! A- grade.\n"); if ((Grade <= 79) && (Grade >= 77)) printf("Very Good! B+ grade.\n"); if ((Grade <= 76) && (Grade >= 74)) printf("Very Good! B grade.\n");

CALCULATE COURSE GRADE if ((Grade <= 73) && (Grade >= 70)) printf("Very Good! B- grade.\n"); if ((Grade <= 69) && (Grade >= 67)) printf("Good! C+ grade.\n"); if ((Grade <= 66) && (Grade >= 64)) printf("Good! C grade.\n"); if ((Grade <= 63) && (Grade >= 60)) if ((Grade <= 59) && (Grade >= 57)) printf("Acceptable! D+ grade.\n"); if ((Grade <= 56) && (Grade >= 54)) printf("Acceptable! D grade.\n"); if ((Grade <= 53) && (Grade >= 50)) printf("Acceptable! D- grade.\n"); if ((Grade <= 49)) printf("Sorry! F grade.\n"); }

Practice! The traffic light program (nested ifs) A program that displays the recommended actions depending on the color of a traffic light. This program uses nested if statements.

Practice! Traffic light /* The traffic light program (nested ifs) */ #include <stdio.h> int main (void) { char colour; /* ask user for colour */ printf ("Enter the colour of the light (R, G or Y): "); scanf ("%c", &colour); /* test if colour is red */ if (colour == 'r' || colour == 'R') printf ("STOP! \n"); else if (colour == 'y' || colour == 'Y') /* yellow colour test */ printf ("CAUTION! \n"); else if (colour == 'g' || colour == 'G') /* green colour test */ printf ("GO! \n"); else /* if not Y or G or R then invalid colour */ printf ("INVALID COLOUR! \n"); return (0); }

SWITCH

C Switch C has built in multiple-branch selection statement, called switch, which successively tests the value of an expression against a list of integer or character constants floating point and double are not allowed. Switch statement is often used to process keyboard commands, such as menu selection. When a match is found ,the statements associated with that constant are executed. The value of expression is tested against the values, one after another, of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed, until the break statement or the end of the switch statement is reached. The default statement is executed if no matches are found. The default is optional, and if it is not present, no action takes place if all matches fail.

C Switch To make selection out of several choices Very Similar to if … else … But probably easier way to code multiple if … else … switch (selection){ case choice1 : (statement1); break; … default : (statementN); } switch, case, break, default: ‘C’ reserved words selection: A ‘C’ expression, can be either int or char. choice: required match, must be of same type as expression1.

Switch Statement The switch statement is a useful alternative for multiple branches (not just true and false). It works not with conditions but with control values. The control values must be int or char only, never double. The control values must be discrete, never ranges.

NOTE!!! If SELECTION matches any of the CHOICES, then the corresponding statement will be executed. DEFAULT is used when no match is made, then this option will be executed. BREAK is used to get out of terminate the SWITCH statement. Nested switch statements can be used if required.

/* PROGRAM # 12 */ /* PROGRAM #12 */ /* USE OF IF STATEMENT FOR A MENU SYSTEM */ #include <stdio.h> #define TGPA 4.3 #define CGPA 3.00 #define CPS125 'A’ main (){ int choice; /*Get the user's selected option*/ printf("Select one of the following choice:\n"); printf("1)TGPA , 2)CGPA, 3)CPS125\n"); scanf("%d",&choice); /* Print the result based on the input */ if (choice == 1) printf("Your term GPA is: %3.2f.\n",TGPA); else if (choice == 2) printf("Your Cumulative GPA is: %3.2f.\n",CGPA); if (choice == 3) printf("Your grade in CPS125 is: %c. ",CPS125); printf("The selected option does not exist!"); }

PRACTICE! /* PROGRAM # 13 */ /* PROGRAM #13 */ /* USE OF SWITCH STATEMENT */ #include <stdio.h> #define TGPA 4.3 #define CGPA 3.00 #define CPS125 'A' main (){ int choice; /*Get the user's selected option*/ printf("Select one of the following choice:\n"); printf("1)TGPA , 2)CGPA, 3)CPS125\n"); scanf("%d", &choice); /* Using switch statement to print the result based on the input */ switch (choice ){ case 1: printf("Your term GPA is: %3.2f.\n",TGPA); break; case 2: printf("Your Cumulative GPA is: %3.2f.\n",CGPA); case 3: printf("Your grade in CPS125 is: %c. ",CPS125); default: printf("The selected option does not exist!"); } }

PRACTICE! /* PROGRAM # 14 */ /* USE OF IF_ELSE STATEMENT AND SWITCH *//* This program is not complete yet but at this point we don’t know enough to fix it*/ #include <stdio.h> main( ){ char choice; float course1=0, course2=0, course3=0; float sum=0, TGPA; /* Make a selection from the menu */ printf("Select one of the following choice:\n"); printf("a)Get the grades for 3 courses, \n”); printf("b)Calculate the term GPA [CGPA],\n"); printf("c)Print course and GPA information,\n"); scanf("%c", &choice); /* Should work for upper case & lower case */ if ( choice == ‘a’ || choice == ‘A’) choice= ‘a’; if ( choice == ‘b’ || choice == ‘B’) choice= ‘b’; if ( choice == ‘c’ || choice == ‘C’) choice= ‘c’;

switch(choice){ case ‘a’:{ printf("Pls enter the grade for the 1st course: "); scanf("%f", &course1); printf("Pls enter the grade for the 2nd course: "); scanf("%f", &course2); printf("Pls enter the grade for the 3rd course: "); scanf("%f", &course3); } break; case ‘b’:{ if (course1 == 0 && course2 == 0 && course3== 0 ){ printf(“You need to provide the grades first and then try to calculate the GPA.\n”); } else{ sum=course1+course2+course3; TGPA=sum/3.0; } } break; case 'c':{ if (TGPA == 0 ){ printf(“Need to provide the grades first & then calculate the GPA, & try this option.\n”); } else{ printf(“Course#1: %f\n”, course1); printf(“Course#2: %f\n”, course2); printf(“Course#3: %f\n”, course3); printf(“Your term GPA is: %f\n”, TGPA); }} break; default: printf("Sorry wrong selection! Pls try again!\n"); }}

Important EXTRA Practice!

Expressions -Identify variables You could have A+-Z%B if they are non zero and integer. You could not have the expression :ab-cd+3bx After each operation we must have an operand: x+xy-z Look at the ( )well. A+(b+c)-(a-d) Do not use reserved words: void ,char. You could use soft rules: A standard identifier is a name used by C but is not a reserved word. printf, scanf are examples of standard identifiers. Be careful we must use functions in C for math .

Expressions -x- y*z……..-x then y*z then –x-result of the second step. (x<y || x<z) && x>0.0 …first && You can also use parentheses to clarify the meaning of the expression. If x,min,max are type double ,the C compiler interprets the expression x+y<min+max correctly as: (x+y)<(min+max)

Character Comparisons Expression Value ‘9’> ‘0’ 1 (true) ‘a’< ‘e’ ‘B’<= ‘A’ 0(false) ‘Z’== ‘z’ ‘a’<= ‘A’ System dependent ‘a’<= ch && ch <= ‘z’ 1 (true) if ch is a lowercase letter