CSCI 123 Introduction to Programming Concepts in C++

Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Chapter 8 Selection 8-1

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Lecture 2 Notes: Flow of Control

While Loop. 6. Iteration

Object Oriented Software Design

Object Oriented Software Design

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Two-way selection. Branching and Looping

Conditions & Boolean Expressions

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Chapter 5. Selection 5-1

JavaScript: Control Statements I

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

The While Loop. Objectives. Textbook. WHILE Loops

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Chapter One Introduction to Programming

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Sources: On the Web: Slides will be available on:

Writing Control Structures

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Computer Programming I

Statements and Control Flow

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

#820 Computer Programming 1A

Computer Programming I & II*

El Dorado Union High School District Educational Services

Example of a Java program

Computer Programming I

6. Control Structures

Java Basics: Data Types, Variables, and Loops

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

UEE1302 (1102) F10 Introduction to Computers and Programming

Chapter 2 Introduction to Java programming

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Informatica e Sistemi in Tempo Reale

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Pseudo code Tutorial and Exercises Teacher s Version

Moving from C++ to VBA

VB.NET Programming Fundamentals

LOOPS CHAPTER CHAPTER GOALS

Passing 1D arrays to functions.

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Introduction to Java

Flowchart Techniques

Selection Statements

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Visual Logic Instructions and Assignments

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

ALGORITHMS AND FLOWCHARTS

Keil C51 Cross Compiler

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Iteration CHAPTER 6. Topic Summary

Answers to Review Questions Chapter 7

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

Moving from CS 61A Scheme to CS 61B Java

A brief introduction to C++ and Interfacing with Excel

C++ INTERVIEW QUESTIONS

An Incomplete C++ Primer. University of Wyoming MA 5310

13 Classes & Objects with Constructors/Destructors

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Fundamentals of Programming and Software Development Lesson Objectives

Algorithm & Flowchart & Pseudo code. Staff Incharge: S.Sasirekha

Notes on Algorithms, Pseudocode, and Flowcharts

J a v a Quiz (Unit 3, Test 0 Practice)

The C Programming Language course syllabus associate level

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Software Engineering Techniques

Pemrograman Dasar. Basic Elements Of Java

Curriculum Map. Discipline: Computer Science Course: C++

I PUC - Computer Science. Practical s Syllabus. Contents

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

River Dell Regional School District. Computer Programming with Python Curriculum

Common Beginner C++ Programming Mistakes

if and if-else: Part 1

AP Computer Science Java Subset

Java Interview Questions and Answers

C++FA 5.1 PRACTICE MID-TERM EXAM

Python Programming: An Introduction To Computer Science

Unit 6. Loop statements

Conditional Statements Summer 2010 Margaret Reid-Miller

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Data Structures. Algorithm Performance and Big O Analysis

What is the consequences of no break statement in a case.

TIP: To access the WinRunner help system at any time, press the F1 key.

The if Statement and Practice Problems

Transcription:

CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe More Flow

Using Boolean Expressions Multi-way Branches More about C++ Loop Statements Designing Loops

Questions???

Some Rules If both operands are type int Then the result is an int type 23 * 38 = integer result 23 / 38 = integer result If one of the operands is a double Then the result is a double type 23.56 * 38 = double result 23.56 / 38 = double result 5 / 2.0 = double result

Variable Types and Operations What results from the following operations? 2+2 2.3 * 4.0 3/2 3.0/2 coercion.cpp

Type Coercion Type Coercion: automatic conversion of an operand to another data type Promotion: convert to a higher type Demotion: convert to a lower type

Rules Are 1) When operating on values of different data types, the lower one is promoted to the type of the higher one. 2) When using the = operator, the type of expression on right will be converted to type of variable on left

What s the output? int main() { bool operand1 = 0; int operand2 = 23; bool result; result = operand1 + operand2; cout << "Result = " << result << endl; return 0; // you don t want to do this coercion2.cpp

if-else statement (basic structure) if(count == 1) { do some work else if(count == 2) { do some other work else { do some other work

while and do/while loops while(count < 9) { do some work do { do some work while(count < 9);

while loops int count = 0; while(count < 3) { count = 01 23 cout << Count is << count << endl; count++; cout << I m out!!!\n ;

Counter-Control Loop Counter-controlled loops are those loops that are executed a fixed number of times. The number of iterations is known before commencing the loop. int i = 1; while (i <= 5) { cout << "Square of " << i; cout << " is " << (i * i); cout << endl; ++i;

Sentinel-Control Loop Event-controlled loops are those loops that are executed an indefinite number of times until some condition occurs. const int SENTINEL = -1; int posint; int sum = 0; cout << Enter number: \n ; cin >> posint; while (posint!= SENTINEL) { sum += posint; cout << Enter number: \n ; cin >> posint ;

Pseudocode Informal language Doesn t execute on a computer Helps with developing algorithms Described with some executable statements Can be easily translated into C++

Pseudocode Example if(sum < 100.00) { // calculate shipping // with UPS ground // process order else { // free shipping // no calculation // process order

Pseudocode Example cout << Your current salary? cin >> salary Calculate the user s retro pay for six months and cout << retro pay Calculate the new annual salary and cout << annual salary Calculate the new monthly salary and cout << new monthly salary

Boolean Expressions Type bool allows declaration of variables that have a value of true or false Operators <, >,!=, ==, <=, >= &&,,! bool executeif = true; if(executeif) { cout << executed if\n ; ifexpressions.cpp

&& - Truth tables if ( gender == 1 && age >= 65 ) seniorfemales++; Exp1 Expr2 Expr1 && Expr2 False False False False True False True False False True True True

- Truth tables if ((semesteraverage >= 90) (finalexam >= 90)) cout << "Student grade is A" << endl; Exp1 Expr2 Expr1 Expr2 False False False False True True True False True True True True

Truth Table Example

Short Circuit Evaluations && - logical and - logical or if(x > 3 y > 3) cout << x > 3 or y > 3 << endl;

bool type Evaluates to a true or false value New to C++ C uses 0 (zero) for false and a positive integer for true Side effects of C This is a compilation error in Java

Enums Enumerations are types with a set of integer values 0 1 2 enum Speed { FAST, NORMAL, SLOW ; Speed speed; // expects one of the enums Enums are capitalized because they are defined as constants They are user-defined types, not given to us like int, char, double, etc.

Enums Can be set to explicit values or not enum Speed { FAST = 120, NORMAL = 65, SLOW = 20 ; if(speed == FAST) { // mash the pedal else if(speed == NORMAL) { // let mom drive else if(speed == SLOW) { // let grandma drive

Blocks of Code if(freeway == 91) { // prepare to go slow else if(freeway!= 91 && day == FRIDAY) { // prepare to stop

Is the following legal? int temperature = 80; if(temperature >= 100) { string msg = "Wow scorching day!\n"; else if(temperature >= 90) { string msg = "It's a hot day!\n"; else if(temperature >= 80) { string msg = "Not bad!\n"; else { string msg = "Wonderful weather!\n"; cout << msg << endl; Assume it s written in the main()

Nested if, if/else string grade; // declaration and initialization of // finalscore & midterm if (finalscore >= 90) if (midterm >= 90) grade = A+ ; else grade = A ; else if (finalscore >= 80) grade = B ; else if (finalscore >= 70) grade = C ; else grade = F ; cout << grade= << grade << endl;

Who owns the else? if (a >= 5) c = c + 1; if (b < 20) b = 2; else d = 5; if (a >= 5) { c = c + 1; if (b < 20) b = 2; else { d = 5; // why the second set of // { braces

Nested if, if/else string grade; // declaration and initialization of // finalscore & midterm if (finalscore >= 90) { if (midterm >= 90) { grade = A+ ; else { grade = A ; else if (finalscore >= 80) { grade = B ; else if (finalscore >= 70) { grade = C ; else { grade = F ; cout << grade= << grade << endl;

Block rules { { { { { { { { { { { OK OK CANNOT

multi-way if/else example int score = 8; char gpa = ; if (score >= 9) { gpa = A ; else if (score >= 8) { gpa = B ; else if (score >= 7) { gpa = C ; else { gpa = F ; cout << grade= << gpa; // value of gpa? score = 8 gpa declared, initialized false true gpa = B display gpa as B What is advantage of the additional elses?

Multi-way if/else advantage int score = 8; char gpa = ; if (score >= 9) { gpa = A ; else if (score >= 8) { gpa = B ; else if (score >= 7) { gpa = C ; else { gpa = F ; cout << grade= << gpa; // value of gpa? o o o o o int score = 8; char gpa = D ; if (score >= 9) gpa = A ; if (score >= 8) gpa = B ; if (score >= 7) gpa = C ; cout << gpa; // value of gpa? o o

multi-way if/else example int score = 8; char gpa = ; if (score >= 7) { gpa = C ; else if (score >= 8) { gpa = B ; else if (score >= 9) { gpa = A ; else { gpa = F ; cout << grade= << gpa; // value of gpa? score = 8 gpa declared, initialized true gpa = C skip the else block o o o o o o display gpa=c still WRONG

Switch Statement Syntax: switch (value) { // must be an integal result case value1: statements; break; case valuen: statements; break; default: statements;...

switch statement char??? char drink = ; Why? cin >> drink; switch(drink) { case 'a': price += 3.50; break; case 'b': Case expressions must be constant price += 3.00; integer expressions or literals, and must break; be unique in the switch statement default : drink = 'q'; break;

more switch What happens with the following code? If break statements are not used with the case statements, execution falls through to the next case

Break statement Used to stop execution in the current block Also used to exit a switch statement Useful to execute a single case statement without executing the statements following it Can be used to break out of loop blocks as well as switch blocks

switch statements Contains case labels Optional default case Similar to the if/else if statement switch(expression) { case a : break; Controlling Expression

number++ vs ++number (number++) returns the current value of number, then increments number An expression using (number++) will use the value of number BEFORE it is incremented (++number) increments number first and returns the new value of number An expression using (++number) will use the value of number AFTER it is incremented Number has the same value after either version!

Increment and Decrement Operators Pre-increment Operator ++a int a = 2; int b = (++a)*22; Post-increment Operator a++ int a = 2; int b = (a++)*22;

for loop structure syntax for (<initializing statement>; <continuation assertion>; <increment statement>) { <body statement>;... <body statement>;

for statement

For code example do { cout << Display # << i; i += 2; while ( i <= 10 ); for (int j = 0; j <= 10; j+=2 ) { cout << For Loop Display # << j;

Break and Continue break quits the loop without executing the rest of the statements in the loop. Used in switch statements Can be used in loops, but not common interrupts the current loop (or a switch case) continue stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration. Executes if continuation condition is true. used with loops, but not common interrupts the current loop

Break Example for(int i = 0; i < 10; i++) { if(i == 5) break; cout << i is << i << endl; i only lives in the for loop. This is known as variable scope. Output: i is 0 i is 1 i is 2 i is 3 i is 4

Continue Example for(int i = 0; i < 10; i++) { if( i < 5 ) continue; cout << i is << i << endl; i only lives in the for loop. This is known as variable scope. Output: i is 5 i is 6 i is 7 i is 8 i is 9

Nested for loop for(int j = 0; j < 5; j++) { cout << "outer: j is " << j << endl; for(int i = 0; i < 5; i++) { cout << " inner: i is " << i << endl;

What does the following output? for (int a = 1; a <= 1; a++) { cout << a++; cout << a;

Debugging Loops Common errors involving loops include Off-by-one errors in which the loop executes one too many or one too few times Infinite loops usually result from a mistake in the Boolean expression that controls the loop

Fixing Off By One Errors Check your comparison: should it be < or <=? Check that the initialization uses the correct value Does the loop handle the zero iterations case?

Fix Infinite Loops Check the direction of inequalities: < or >? Test for < or > rather than equality (= =) Check to see that you didn t use the assignment operator (=) instead of the comparison (==)

Starting Over Sometimes it is more efficient to throw out a buggy program and start over The new program will be easier to read The new program is less likely to be as buggy You may develop a working program faster than if you repair the bad code The lessons learned in the buggy code will help you design a better program faster