Chapter 2 - Control Structures

Size: px
Start display at page:

Transcription

1 Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating Algorithms: Case Study 1: Counter-Controlled Repetition) 2.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2: Sentinel-Controlled Repetition) 2.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3: Nested Control Structures)

2 2 2.1 Introduction Before writing a program Have a thorough understanding of problem Carefully plan your approach for solving it While writing a program Know what building blocks are available Use good programming principles

3 3 2.2 Algorithms Computing problems Solved by executing a series of actions in a specific order Algorithm a procedure determining Actions to be executed Order to be executed Example: recipe Program control Specifies the order in which statements are executed

4 4 2.3 Pseudocode Pseudocode Artificial, informal language used to develop algorithms Similar to everyday English Not executed on computers Used to think out program before coding Easy to convert into C++ program Only executable statements No need to declare variables

5 2.4 Control Structures 5 Sequential execution: statements executed in order cout << "Welcome "; cout << "to "; cout << "C++"; Transfer of control: Next statement executed not next one in sequence cout << "Welcome"; cout << " to"; if (course==105) cout << " C!"; else if (course==181) cout << " C++! "; else { // Print error message and exit cerr << "Unknown course"; exit(-1); }

6 6 2.4 Control Structures 3 control structures (Bohm and Jacopini) are sufficient to express any algorithm Sequence structure Programs executed sequentially by default Selection structures if, if/else, switch Repetition structures while, do/while, for goto's are bad, mmm 'kay? "Go To Statement Considered Harmful" Edsger W. Dijkstra, CACM Mar Communications of the ACM, Vol. 11, No. 3, March 1968, pp

7 Example of "goto" statement cout << "Welcome"; cout << " to"; cout << "Welcome"; cout << " to"; if (course == 181) goto greet181; if (course == 181) if (course == 105) cout << " C++!" << endl; goto greet105; else if (course == 105) cout << " C!" << endl; cerr << "\nerror: Unknown Course" << endl; return -1; // exit with error else status { greet181: cerr << "\nerror: Unknown Course cout << " C++!" << endl; goto endprogram; return -1; // exit with error st greet105: cout << " C!" << endl; } goto endprogram; cout << "Goodbye for now" << endl; endprogram: cout << "Goodbye for now" << endl; return 0; // exit successfully. return 0; // exit successfully. 7

8 Dijkstra Letter Quotes...the quality of programmers is a decreasing function of the density of go to statements in the programs they produce....the go to statement should be abolished from all "higher level" programming languages (i.e. everything except, perhaps, plain machine code). we should... shorten the conceptual gap between the static program and the dynamic process, to make the correspondence between the program (spread out in text space) and the process (spread out in time) as trivial as possible. The go to statement as it stands is just too primitive; it is too much an invitation to make a mess of one's program Edsger W. Dijkstra Go To Statement Considered Harmful, Communications of the ACM, Vol. 11, No. 3, March 1968, pp

9 More Dijkstra Quotes 9 "Computer Science is no more about computers than astronomy is about telescopes." "A Programming Language is a tool that has profound influence on our thinking habits." "The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague." "Progress is possible only if we train ourselves to think about programs without thinking of them as pieces of executable code." "Program testing can best show the presence of errors but never their absence."

10 2.4 C++ keywords Cannot be used as identifiers or variable names 10 Keywords common to the C and C++ programming languages auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigmed void volatile while C++ only keywords asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t

11 Flowchart 2.4 Control Structures Graphical representation of an algorithm Special-purpose symbols connected by arrows (flowlines) Rectangle symbol (action symbol) Any type of action Oval (or circle) symbol Beginning or end (of a program, or a section of code) Single-entry/single-exit control structures ("no gotos") Connect exit point of one to entry point of the next Control structure stacking product <= 1000 false grade >= 60 false true true 11 product = 2 * product; print Passed

12 2.5 if Selection Structure 12 Selection structure: Choose among alternative courses of action If student s grade is greater than or equal to 60 Print Passed if ( grade >= 60 ) cout << "Passed"; Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.) Diamond symbol (decision symbol) grade >= 60 false Indicates decision is to be made Contains an expression that can be true or false Note: in C/C++, every expression has true/false value: zero implies false, nonzero implies true. Example: if ( 3-4) is interpreted as "true". if structure has single-entry/single-exit true print Passed

13 2.6 if/else Selection Structure 13 if Performs action if condition true if/else Different actions if conditions true or false if student s grade is greater than or equal to 60 print Passed else print Failed if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

14 2.6 Ternary conditional operator (?:) 14 Three arguments: (condition, value if true, value if false) cout << ( grade >= 60? Passed : Failed ); Condition Value if true Value if false

15 if/else if ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; Comparison 15 vs. ternary operator cout << ( grade >= 60? Passed : Failed ); false grade >= 60 true print Failed print Passed

16 if/else Selection Structure Nested if/else structures One inside another, test for multiple cases Once condition met, other statements skipped if student s grade is greater than or equal to 90 Print A else if student s grade is greater than or equal to 80 Print B else if student s grade is greater than or equal to 70 Print C else if student s grade is greater than or equal to 60 Print D else Print F

17 2.6 if/else Selection Structure 17 Example if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // cout << "B"; else if ( grade >= 70 ) // cout << "C"; else if ( grade >= 60 ) // cout << "D"; else // less than 60 cout << "F";

18 2.6 if/else Selection Structure 18 Compound statement Set of statements within a pair of braces if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } Without braces, cout << "You must take this course again.\n"; always executed Block Set of statements within braces

19 2.6 Indentation Rules Deitel/Deitel prefer: if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } Conrad prefers: if ( grade >= 60 ) cout << "Passed.\n"; else { } cout << "Failed.\n"; cout << "You must take this course again.\n"; Whatever you do, be consistent. (choose one way or other way, otherwise may lose points...) 19

20 2.7 while Repetition Structure Repetition structure Action repeated while some condition remains true while there are more items on my shopping list Purchase next item and cross it off my list while loop repeated until condition becomes false Example int product = 2; while ( product <= 1000 ) product = 2 * product; 20 product < = 1000 true product = 2 * product false

21 2.8 Formulating Algorithms (Counter-Controlled Repetition) 21 Counter-controlled repetition Loop repeated until counter reaches certain value Definite repetition Number of repetitions known Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available. Determine the class average on the quiz. We know there are exactly 10 scores. So, we are going to need to repeat "something" exactly 10 times. There may be some stuff to do first to set things up, then some stuff to do at the end to finish up, as well.

22 2.8 Pseudocode for finding class average (counter controlled repetition) 22 Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available. Determine the class average on the quiz. Pseudocode for example: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Next: C++ code for this example

23 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled repetition. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function main begins program execution 10 int main() 11 { 12 int total; // sum of grades input by user 13 int gradecounter; // number of grade to be entered next 14 int grade; // grade value 15 int average; // average of grades // initialization phase 18 total = 0; // initialize total 19 gradecounter = 1; // initialize loop counter 20 Outline fig02_07.cpp (1 of 2) Prentice Hall, Inc. All rights reserved.

25 2.9 Formulating Algorithms (Sentinel-Controlled Repetition) 25 Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run Unknown number of students How will program know when to end? Sentinel value Indicates end of data entry Loop ends when sentinel input Sentinel chosen so it cannot be confused with regular input -1 in this case

26 2.9 Formulating Algorithms (Sentinel- Controlled Repetition) 26 Top-down, stepwise refinement Begin with pseudocode representation of "top" (whole problem) Determine the class average for the quiz Then, divide top into smaller tasks, list in order Determine the class average for the quiz Initialize variables Input, sum and count the quiz grades Calculate and print the class average

27 Many programs have three phases Helps break up programs for top-down refinement Initialization Initializes the program variables Processing Input data, adjusts program variables Termination Calculate and print the final results Determine the class average for the quiz Initialize variables Input, sum and count the quiz grades Calculate and print the class average

28 Refinement of the first two phases... Refine the initialization phase Processing Initialize variables goes to Initialize total to zero Initialize counter to zero Input, sum and count the quiz grades goes to Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)

29 Refinement of the termination phase Termination Calculate and print the class average goes to If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print No grades were entered Next: C++ program

30 1 // Fig. 2.9: fig02_09.cpp 2 // Class average program with sentinel-controlled repetition. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::fixed; 9 10 #include <iomanip> // parameterized stream manipulators using std::setprecision; // sets numeric output precision // function main begins program execution 15 int main() 16 { Data type double used to represent 17 int total; // sum of grades decimal numbers. 18 int gradecounter; // number of grades entered 19 int grade; // grade value double average; // number with decimal point for average // initialization phase 24 total = 0; // initialize total 25 gradecounter = 0; // initialize loop counter Outline fig02_09.cpp (1 of 3) Prentice Hall, Inc. All rights reserved.

32 49 // display average with two digits of precision 50 cout << "Class average is " << setprecision( 2 ) 51 << fixed << average << endl; } // end if part of if/else else // if no grades were entered, output appropriate message 56 cout << "No grades were entered" << endl; return 0; // indicate program ended successfully } // end function main Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is Outline fig02_09.cpp (3 of 3) fig02_09.cpp output (1 of 1) fixed forces output setprecision(2)prints to print two digits past in fixed point format decimal (not point (rounded to fit precision). scientific notation). Also, forces trailing zeros Programs and that use this must include <iomanip> decimal point to print. Include <iostream> Prentice Hall, Inc. All rights reserved.

33 33 Problem statement 2.10 Nested Control Structures A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition". Notice that Program processes 10 results Fixed number, use counter-controlled loop Two counters can be used One counts number that passed Another counts number that fail Each test result is 1 or 2 If not 1, assume 2 Conrad Comments: Probably better to do error checking on input!

34 Nested Control Structures Top level outline Analyze exam results and decide if tuition should be raised First refinement Refine Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised Initialize variables to Initialize passes to zero Initialize failures to zero Initialize student counter to one

35 35 Refine 2.10 Nested Control Structures Input the ten quiz grades and count passes and failures to While student counter is less than or equal to ten { Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter }

36 36 Refine 2.10 Nested Control Structures Print a summary of the exam results and decide if tuition should be raised to Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition Next: C++ program

37 1 // Fig. 2.11: fig02_11.cpp 2 // Analysis of examination results. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function main begins program execution 10 int main() 11 { 12 // initialize variables in declarations 13 int passes = 0; // number of passes 14 int failures = 0; // number of failures 15 int studentcounter = 1; // student counter 16 int result; // one exam result // process 10 students using counter-controlled loop 19 while ( studentcounter <= 10 ) { // prompt user for input and obtain value from user 22 cout << "Enter result (1 = pass, 2 = fail): "; 23 cin >> result; 24 Outline fig02_11.cpp (1 of 2) Prentice Hall, Inc. All rights reserved.

38 25 // if result 1, increment passes; if/else nested in while 26 if ( result == 1 ) // if/else nested in while 27 passes = passes + 1; else // if result not 1, increment failures 30 failures = failures + 1; // increment studentcounter so loop eventually terminates 33 studentcounter = studentcounter + 1; } // end while // termination phase; display number of passes and failures 38 cout << "Passed " << passes << endl; 39 cout << "Failed " << failures << endl; // if more than eight students passed, print "raise tuition" 42 if ( passes > 8 ) 43 cout << "Raise tuition " << endl; return 0; // successful termination } // end function main Outline fig02_11.cpp (2 of 2) Prentice Hall, Inc. All rights reserved.

39 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Passed 6 Failed 4 Outline fig02_11.cpp output (1 of 1) 39 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Passed 9 Failed 1 Raise tuition 2003 Prentice Hall, Inc. All rights reserved.

Introduction to Programming

Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

Chapter 3 Structured Program Development

1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

IS 0020 Program Design and Software Tools

1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

Structured Program Development

Structured Program Development Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Introduction The selection statement if if.else switch The

Structured Program Development in C

1 3 Structured Program Development in C 3.2 Algorithms 2 Computing problems All can be solved by executing a series of actions in a specific order Algorithm: procedure in terms of Actions to be executed

In this chapter you will learn:

1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

BIL101E: Introduction to Computers and Information systems Lecture 8

BIL101E: Introduction to Computers and Information systems Lecture 8 8.1 Algorithms 8.2 Pseudocode 8.3 Control Structures 8.4 Decision Making: Equality and Relational Operators 8.5 The if Selection Structure

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad Outline 1. The if Selection Structure 2. The if/else Selection Structure 3. The switch Multiple-Selection Structure 1. The if Selection

Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

Fundamentals of Programming. Lecture 6: Structured Development (part one)

Fundamentals of Programming Lecture 6: Structured Development (part one) Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu edu Sharif University of Technology Computer Engineering Department Outline Algorithms

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

C How to Program, 6/e Before writing a program to solve a particular problem, it s essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. The

Variables. Data Types.

Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

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

University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

IS 0020 Program Design and Software Tools

1 Course Information 2 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 1 May 10, 2004 Lecture: James B D Joshi Mondays: 6:00-8.50 PM One (two) 15 (10) minutes break(s)

Programming. C++ Basics

Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CSE123 LECTURE 3-1 Program Design and Control Structures Repetitions (Loops) 1-1 The Essentials of Repetition Loop Group of instructions computer executes repeatedly while some condition remains true Counter-controlled

Tokens, Expressions and Control Structures

3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

, ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

C++ PROGRAMMING SKILLS Part 2 Programming Structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

JavaScript: Control Statements I

7 JavaScript: Control Statements I OBJECTIVES In this chapter you will learn: Basic problem-solving techniques. To develop algorithms through the process of top-down, stepwise refinement. To use the if

1 7 JavaScript: Control Statements I 2 Let s all move one place on. Lewis Carroll The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

Programming with C++ Language

Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language

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

Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

2.11 Assignment Operators 1 Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression;

Fundamental of Programming (C)

Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

C: How to Program. Week /Mar/05

1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

CSCI 123 Introduction to Programming Concepts in C++

CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe C++ Basics C++ layout Include directive #include using namespace std; int main() { } statement1; statement; return 0; Every program

Assignment Operations

ECE 114-4 Control Statements-2 Dr. Z. Aliyazicioglu Cal Poly Pomona Electrical & Computer Engineering Cal Poly Pomona Electrical & Computer Engineering 1 Assignment Operations C++ provides several assignment

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

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.

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. B. Outputs to the console a floating point number f1 in scientific format

Basics of C++ // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!

Basics of C++ // my first program in C++ Hello World! cout

1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

REPETITION CONTROL STRUCTURE LOGO

CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

EEE145 Computer Programming

EEE145 Computer Programming Content of Topic 2 Extracted from cpp.gantep.edu.tr Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

Introduction to C Programming

1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

1 EEE1008 C Programming

1 1 EEE1008 C Programming Dr. A.M. Koelmans 2 Administrative details Dr. A.M. Koelmans Location: Merz Court, room E4.14 Telephone: 8155 Web: www.staff.ncl.ac.uk/albert.koelmans/ E-mail: albert.koelmans@newcastle.ac.uk

Chapter 3 Structured Program Development in C Part II

Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 3.7 The while Iteration Statement An iteration statement (also called

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

Why Is Repetition Needed?

Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

Introduction. C provides two styles of flow control:

Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

Control Statements. Musa M. Ameen Computer Engineering Dept.

2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

Introduction to Programming

Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

Short Notes of CS201

#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions

UEE1302 (1102) F10: Introduction to Computers and Programming

Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Objectives By the end of this section you should be able to:

Programming in C++ 4. The lexical basis of C++

Programming in C++ 4. The lexical basis of C++! Characters and tokens! Permissible characters! Comments & white spaces! Identifiers! Keywords! Constants! Operators! Summary 1 Characters and tokens A C++

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

Compiler Construction. Lecture 10

Compiler Construction Lecture 10 Using Generated Scanner void main() { FlexLexer lex; int tc = lex.yylex(); while(tc!= 0) cout

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

Fundamentals of Programming

Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

Visual Basic 2010 How to Program Before writing a program to solve a problem, you should have a thorough understanding of the problem and a carefully planned approach. When writing a program, it s also

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

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

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

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

Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

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

Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

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

C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5 APPENDIX E : ASCII CHARACTER SET... 6 APPENDIX F : USING THE GCC COMPILER

Fundamentals of Programming Session 7

Fundamentals of Programming Session 7 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

Computer Programming : C++

The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

Chapter 2

Chapter 2 Topic Contents The IO Stream class C++ Comments C++ Keywords Variable Declaration The const Qualifier The endl, setw, setprecision, manipulators The scope resolution operator The new & delete

Functions and Recursion

Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

Introduction to C# Applications

1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

Fundamental of Programming (C)

Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 5 Structured Program Development Department of Computer Engineering How to develop

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

Fundamentals of Programming

Fundamentals of Programming Lecture 5 - Structured Program Development Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad How to develop a program? Requirements Problem Analysis

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

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

Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

Chapter 2. C++ Basics

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing