Introduction to Programming

Similar documents
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Increment and the While. Class 15

Why Is Repetition Needed?

Introduction to Programming

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

REPETITION CONTROL STRUCTURE LOGO

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Exceptions, Case Study-Exception handling in C++.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

In this chapter you will learn:

Add Subtract Multiply Divide

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

LECTURE 5 Control Structures Part 2

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

CSCE 206: Structured Programming in C++

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Programming Language. Functions. Eng. Anis Nazer First Semester

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

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

do { statements } while (condition);

C++ Programming: From Problem Analysis to Program Design, Third Edition

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Control Structures of C++ Programming (2)

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 5: Control Structures II (Repetition)

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

DELHI PUBLIC SCHOOL TAPI

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Local and Global Variables

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Linked List using a Sentinel

EP241 Computing Programming

1 Unit 8 'for' Loops

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Name SECTION: 12:45 2:20. True or False (12 Points)

CSI33 Data Structures

Introduction to Computer Science Midterm 3 Fall, Points

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Chapter 3. More Flow of Control

Lab Instructor : Jean Lai

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CS2255 HOMEWORK #1 Fall 2012

Repetition Structures

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

INTRODUCTION TO COMPUTER SCIENCE - LAB

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Topics. Functions. Functions

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Fundamentals of Programming CS-110. Lecture 2

Looping. Arizona State University 1

Computer Programming : C++

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

Lecture 7: General Loops (Chapter 7)

EP578 Computing for Physicists

CSCI 1061U Programming Workshop 2. C++ Basics

A SHORT COURSE ON C++

Introduction to Programming

Computer Programming

Decision Making and Loops

Computer Science II Lecture 1 Introduction and Background

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Chapter 1 INTRODUCTION

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Introduction to Programming using C++

Ch 6. Functions. Example: function calls function

Introduction. C provides two styles of flow control:

Transcription:

Introduction to Programming Summer Term 2015 Dr. Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 State: May 6, 2015 Betriebssysteme / verteilte Systeme Introduction to Programming (1) i Introduction to Programming Summer Term 2015 5 More Statements Betriebssysteme / verteilte Systeme Introduction to Programming (1) 112

5 More Statements... Contents The switch statement (a multi-if ) Loops An example: prime numbers Assertions Betriebssysteme / verteilte Systeme Introduction to Programming (1) 113 5.1 The switch Statement A calculator multiple if statements char command; cin >> command; if ( command == + ) add(); else if ( command == - ) subtract(); else if ( command == * ) multiply(); else if ( command == / ) divide(); else cout << "unknown command\n ; Betriebssysteme / verteilte Systeme Introduction to Programming (1) 114

5.1 The switch Statement... A better way: the switch statement char command; cin >> command; switch ( command ) { case + : add(); case - : subtract(); case * : multiply(); case / : divide(); default: cout << "unknown command\n"; Betriebssysteme / verteilte Systeme Introduction to Programming (1) 115 5.1 The switch Statement... General form of a switch statement switch ( expression ) { // any C++ expression case constant1: // test for equality statement-list; case constant2: case constant3: statement-list; // leave the switch statement // (optional) default: statement-list; // handle everything else (optional) Betriebssysteme / verteilte Systeme Introduction to Programming (1) 116

5.1 The switch Statement... Quiz: What is the output? int number; cin >> number; switch ( number ) { case 0: cout << "zero\n"; case 1: case 2: cout << "one or two\n"; case 3: cout << "three\n"; default: cout << "not between zero and three\n"; Betriebssysteme / verteilte Systeme Introduction to Programming (1) 117 5.1 The switch Statement... A style-guide for switch Use break (almost) always If you do not use break, add a comment to show that you really mean it: case 1: do_something(); // fall through case 2: do_something_additional(); // fall through case 3: do_what_is_needed_for_1_2_and_3(); Always use a default clause to handle unforeseen cases This helps debugging later on! Betriebssysteme / verteilte Systeme Introduction to Programming (1) 118

5.2 Loops Repeating things Often, we have to repeat a step of an algorithm several times In C++, this is achieved with loops: while loops do while loops for loops Each execution of the loop s statements (its body) is called an iteration Betriebssysteme / verteilte Systeme Introduction to Programming (1) 119 5.2 Loops... while loops Syntax: while ( expression ) statement ; Example: cout << "How many hello s?\n"; cin >> number; while ( number > 0 ) { cout << "Hello!\n"; number--; Expression is evaluated before the loop body is entered The body may thus not be entered (executed) at all Betriebssysteme / verteilte Systeme Introduction to Programming (1) 120

5.2 Loops... do while loops Syntax: do statement ; while ( expression ); Example: char c; do { cout << "Do it again (y/n)?\n"; cin >> c; while ( c!= n ); Expression is evaluated after the loop body has been executed The body will always be executed at least once Betriebssysteme / verteilte Systeme Introduction to Programming (1) 121 5.2 Loops... Correctness of while and do while The loop expression must eventually become false (0) if not, the loop runs forever! This may be non-trivial (e.g., with if/else statements) Often, we have simple, counting loops, e.g. do this for all integers from 0 to 9 do this 12 times Such a loop typically has some initialization for the counter, a condition, and a step statement (like increment or decrement) Betriebssysteme / verteilte Systeme Introduction to Programming (1) 122

5.2 Loops... for loops for loops prescribe initialization, loop condition, and step Syntax: for ( statement ; expression ; statement ) statement ; // initialization condition step body Example: for ( int i = 0; i < 10; i++ ) { cout << "i = " << i << endl; The variable i is called loop control variable or loop variable Betriebssysteme / verteilte Systeme Introduction to Programming (1) 123 5.2 Loops... for loops... for ( statement ; expression ; statement ) statement ; Some remarks: all statements may also be empty, e.g.: int i = 1; for (; i < 10; ) { cout << "i = " << i << endl; if (i < 5) { i += 1; else { i += 2; statements may be complex (bad style!): for (int i=0; i<10; cout << "i = " << i++ << endl); Betriebssysteme / verteilte Systeme Introduction to Programming (1) 124

5.2 Loops... Nested loops Loops may be inside loops: // int i, j; for ( int i = 0; i < 5; i++ ) { for ( int j = 0; j < 20; j++ ) { cout <<. ; cout << endl; Style: Always use { and for the loop body! Betriebssysteme / verteilte Systeme Introduction to Programming (1) 125 5.2 Loops... Special statements inside a loop body exit the whole loop (without testing the loop expression) continue; exit the loop body and continue with the next iteration Style Guide: avoid the use of break and especially of continue inside loop bodies! it is (often) easier to understand if you do the same with if / else or exceptions ( 10) however, break is nice to use in search loops Betriebssysteme / verteilte Systeme Introduction to Programming (1) 126

5.3 An Example: Prime Numbers // Print all primes <= 100, using naive algorithm. Author: Roland Wismï 1 ller 2 #include <iostream> using namespace std; int main() { //int number, factor; bool prime; cout << 2 << endl; for ( int number = 3; number < 100; number += 2) { prime = true; for (int factor = 3; factor < number; factor += 2) { if (number % factor == 0) { prime = false; if (!prime) continue; // Note: bad style! cout << number << endl; Betriebssysteme / verteilte Systeme Introduction to Programming (1) 127 5.3 An Example: Prime Numbers... (Animierte Folie) cout << 2 << endl; for (number = 3; number < 100; number += 2) { prime = true; for (factor = 3; factor < number; factor += 2) { if (number % factor == 0) { prime = false; if (!prime) continue; cout << number << endl; number: 3 factor: prime: output: 2 Betriebssysteme / verteilte Systeme Introduction to Programming (1) 128

5.4 Assertions Often, you know that some condition always must (or better: should!) hold at a certain place in your program Good practice: include runtime checks of these conditions A good way to do this is via assertions Use #include <assert.h> Then use assert(expression); to check the condition Example: assert(divisor!= 0); When the program reaches an assert() statement and the expression is false (0), the program halts with an error message Beware: do not use side effects, like assert(i++ < 10);! Betriebssysteme / verteilte Systeme Introduction to Programming (1) 129 5.5 Summary switch statement switch ( expression ) { // any C++ expression case constant1: // test for equality statement-list; case constant2: case constant3: statement-list; // leave the switch statement // (optional) default: statement-list; // handle everything else (optional) Betriebssysteme / verteilte Systeme Introduction to Programming (1) 130

5.5 Summary... Loops while ( expression ) statement ; loop body may not be executed at all do statement ; while ( expression ); loop body is executed at least once for ( statement ; expression ; statement ) statement ; counting loop, with counter initialization, loop condition, and step Betriebssysteme / verteilte Systeme Introduction to Programming (1) 131 5.6 Code example using loops int main( void) { int i,j, k; i=j=0; cout << endl << "----- WHILE () {... ------" << endl; while (j<10) ++j; i += j; PRINT2(i,j); i=j=0; while (j<10) i += ++j; PRINT2(i,j); cout << endl << "----- DO {... WHILE (); ----- " << endl; i=j=0; do { PRINT2(i,j); j += 2; i++; while (j<7); Betriebssysteme / verteilte Systeme Introduction to Programming (1) 131

5.6 Code example using loops i=0; cout << "----- FOR ( ; ; ){... :----- " << endl; for ( j=1; j<100; j++); PRINT2(i,j); for ( j=1; (i=j)<7; j++) { PRINT2(i,j); cout << endl << "TEST:" << endl; PRINT2(i,j); cout << "execute loop:"; for ( int i=0, j=100; j>1; i++) { j /= 25; PRINT2(i,j); cout << "outside the loop:"; PRINT2(i,j); Betriebssysteme / verteilte Systeme Introduction to Programming (1) 131