C++ PROGRAMMING SKILLS Part 2 Programming Structures

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

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

Introduction to Programming

In this chapter you will learn:

Chapter 3 Structured Program Development

Chapter 2 - Control Structures

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

Chapter 2 - Control Structures

REPETITION CONTROL STRUCTURE LOGO

Structured Program Development

Chapter 2 - Control Structures

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

Chapter 2 - Control Structures

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

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

Score score < score < score < 65 Score < 50

Introduction to C Programming

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

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

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

Add Subtract Multiply Divide

Why Is Repetition Needed?

Structured Programming. Dr. Mohamed Khedr Lecture 9

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

Chapter 4 C Program Control

Introduction. C provides two styles of flow control:

DELHI PUBLIC SCHOOL TAPI

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

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

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

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

BIL101E: Introduction to Computers and Information systems Lecture 8

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

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

Chapter 5: Control Structures II (Repetition)

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

V3 1/3/2015. Programming in C. Example 1. Example Ch 05 A 1. What if we want to process three different pairs of integers?

LECTURE 5 Control Structures Part 2

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

A Freshman C++ Programming Course

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Flow Control. CSC215 Lecture

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

5. Selection: If and Switch Controls

Chapter 4 C Program Control

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Structured Program Development in C

Control Statements. Musa M. Ameen Computer Engineering Dept.

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

IS 0020 Program Design and Software Tools

Computer Programming C++ (66111)

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

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

Chapter 7. Additional Control Structures

Examination for the Second Term - Academic Year H Mid-Term. Name of student: ID: Sr. No.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Theory of control structures

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

Lecture 10. Daily Puzzle

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Information Science 1

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

Chapter 4: Control Structures I (Selection)

Control Structure and Loop Statements

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

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

Object Oriented Pragramming (22316)

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

CHAPTER 9 FLOW OF CONTROL

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

3 The L oop Control Structure

n Group of statements that are executed repeatedly while some condition remains true

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

1 EEE1008 C Programming

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

C Programming Class I

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

do, while and for Constructs

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

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.

UNIT- 3 Introduction to C++

Information Science 1

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Selection / making decision If statement if-else, if-else-if or nested if Switch Case

Lecture 6. Statements

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

Control Statements: Part Pearson Education, Inc. All rights reserved.

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

DECISION CONTROL AND LOOPING STATEMENTS

204111: Computer and Programming

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

Looping statement While loop

Transcription:

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 1

Control Structures 1. Sequential structure Statements executed in order. Programs executed sequentially by default 2. Selection structures Next statement executed not next one in sequence if, if/else, switch 3. Repetition structures Statement repeatedly executed a number of times while, do/while, for single-entry/single-exit control structures Connect exit point of one control structure to entry point of the next (control-structure stacking). Makes programs easy to build. 2

if Selection Structure Selection structure Choose among alternative courses of action Pseudocode example: If student s grade is greater than or equal to 50 Print Passed If the condition is true Print statement executed, program continues to next statement If the condition is false Print statement ignored, program continues Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.) Translation into C++ If student s grade is greater than or equal to 50 Print Passed if ( grade >= 50 ) cout << "Passed"; 3

if/else Selection Structure if Performs action if condition true if/else Different actions if conditions true or false Pseudocode if student s grade is greater than or equal to 50 print Passed else print Failed Statement C++ code k if ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; false condition true Statement i 4

if/else Selection Structure Compound statement Set of statements within a pair of braces if ( grade >= 50 ) 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 5

if/else Selection Structure More on Compound statement if ( grade >= 50 ){ else cout << "Passed.\n"; cout << Very Good.\n"; } cout << "Failed.\n"; if ( grade >= 50 ){ else{ } cout << "Passed.\n"; cout << Very Good.\n"; } cout << "Failed.\n"; cout << Must take this course again.\n"; 6

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 Example if ( grade >= 90 ) cout << "A"; else if ( grade >= 80 ) cout << "B"; else if ( grade >= 70 ) cout << "C"; else if ( grade >= 60 ) cout << "D"; else cout << "F"; 7

Ternary Operator expression1? expression2 : expression3 x = (y < z)? y : z ; if (a > b) { ans = 10;} else { ans = 25;} a > b? (ans = 10) : (ans = 25) ; ans = (a > b)? 10 : 25 ; 8

switch Control Structure 9 Constructed like if-else-if Used to transfer control Can nest switch control structures Keyword switch followed by expression switch (expression) { statement block } Must use parentheses Must result in integer type value Keyword case only used in switch statement case used to form label case label is constant followed by colon Constant1, constant2, etc must be integer expressions Constant expressions must be unique default optional, used when no match is found break Statement switch (expression) {case constant1: statement1a break; case constant2: statement2a break; default: statements } char x; cin>>x; switch (x) { case 'A': case 'a': cout << "x is A or a\n"; break; case 'B': case 'b': cout << "x is B or b\n"; break; default: cout << "value of x unknown\n";}

switch Control Structure (cont) int n; cin>>n; switch(n>50) { case 1: cout<<"pass\n";//true break; case 0: cout<<"fail\n"; //false break; } int n,k; cin>>n>>k; switch(n+k-3) { case 14: cout<<"pass\n"; break; case -3:cout<<"FAIL\n"; break; default: cout<<"unknown VALUE\n"; } 10

while Repetition Structure Repetition structure Action repeated while some condition remains true Psuedocode 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; 11

while Statement Syntax int prod = 2; while (prod <= 100){ prod = 2 * prod; cout << Product = << prod <<endl;} true condition int prod = 2; while (prod <= 100) false prod = 2 * prod; Statement int i= 0, number = 1; while (number) { cout << Please type a number. << Type 0 (zero) to stop execution.\n ; cin >> number; i++; if (i > 50) break; } 12

The do/while Repetition Structure The do/while repetition structure is similar to the while structure, Condition for repetition tested after the body of the loop is executed Format: do statement while ( condition ); Example (letting counter = 1): Statement do{ cout<<counter<<" ";counter=counter+1; }while (counter <= 10); This prints the integers from 1 to 10 condition All actions are performed at least once. false true 13

do-while Repetition Structure do statement while (Expression); Statement do { cout << Enter a Positive integer: ; cin >> num; } while (num < 0); cout << Thank You! condition false do { cout<< Enter an integer between 1 and 7, please: ; cin>>num; } while (num < 1 num > 7); cout << Thank You Very Much.\n ; true Input Validation Examples 14

do-while and while Examples sum=0; counter=1; while (counter<=100) { sum=sum+counter; counter=counter+1; // increment counter } do{//age validation not equal or less then zero cout<< Enter your Age: ; cin>>age; } while (age<=0); 15

do-while and while Examples // Add even numbers between 1 and 100 sum=0; counter=2; while (counter<=100){ } Question1: sum=sum+counter; counter=counter+2; Write C++ program to Add EVEN numbers together from a 100 input Values Question2: Write C++ program to separately add Even numbers and Odd numbers. Finally prints sumev & sumo 16

Example: Sum Evens // Add only Even number of 100 inputs # include <iostream.h> int main( ) { int num, sum, counter; sum=0; counter=0; do { cout<< Enter a number : ; cin>>num; if(num%2==0) sum = sum + num; counter=counter+1; } while (counter < 100); cout<<sum; return 0; } // end function main 17

Example: sum odds & Evens // separately add Even numbers and Odd numbers. Prints the sum of each # include<iostream.h> int main() { int num, sumeven=0, sumodd=0, counter=0; do { cout<< Enter a number : ; cin>>num; if(num%2==0) else sumeven = sumeven + num; sumodd=sumodd + num; counter=counter+1; } while (counter < 100); cout<< sum of Ever Numbers = <<sumeven<<endl; cout<< sum of Odd numbers = <<sumodd<<endl; return 0; } 18

Assignment Operators 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; can be rewritten as variable operator= expression; Examples of other assignment operators include: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9) 19

The for Repetition Structure The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; Prints the integers from one to ten initialization increment Continue? Statement No semicolon after last expression 20

The for Repetition Structure for loops can usually be rewritten as while loops: initialization; while ( loopcontinuationtest){ } statement increment; Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; 21

Examples Using the for Structure Program to sum the even numbers from 2 to 100 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for 3 #include <iostream.h> 4 5 6 7 8 int main() 9 { 10 int sum = 0; 11 12 for ( int number = 2; number <= 100; number += 2 ) 13 sum += number; 14 15 cout << "Sum is " << sum << endl; 16 17 return 0; 18 } Sum is 2550 22

Examples Using the for Structure Example 1 for(n=1;n<=9;n++) cout<<n; Output 1 2 3 4 5 6 7 8 9 Example 2 sum = 0; for(n=1; n<=5; n++) { cout << Enter a number: ; cin >> num; sum = sum + num; } Cout << sum= << sum; Output Enter a number: 81 Enter a number: 1 Enter a number: 5 Enter a number: 100 Enter a number: 4 Sum= 191 23

Examples Using the for Structure Output x=2; y=10; for(j=2; j<=40; j+=5) for(j=x; j<=2*x*y; j += y/x) cout << j << endl; 2 7 12 17 22 27 32 37 24

Nested For Loop examples Example 1 for(r=1;i<=5;r ++){ for(c=1;c<=5;c++) cout<< * ; cout<<endl; } Output * * * * * * * * * * * * * * * * * * * * * * * * * Example 2 // multiplication table for(x=1; x<=3; x ++) for(y=1; y<=3; y++) cout<<x<< * <<y<< = <<x*y<<endl; Output 1*1=1 1*2=2 1*3=3 2*1=2 2*2=4 2*3=6 3*1=3 3*2=6 3*3=9 25

for Loop and while Loop for (Expr1; Expr2; Expr3) statement Equivalent while Syntax Expr1; while(expr2){ statement Expr3; } Example 1 for(i=1;i<=5;i++) cout<<i; Output 1 2 3 4 5 Example 1 i=1; while(i<=5){ cout<<i; i++; } Output 1 2 3 4 5 26

More examples on for Float index in the for loop float x; for(x=1.0;x<=5.0;x+=0.5) cout<<x<< ; Output 1 1.5 2 2.5 3 3.5 4 4.5 5 Char index in the for loop char ch; for(ch= a ; ch< f ; ch += b - a ) cout << ch << ; Output a b c d e f float ch; for(ch= a ; ch <= c ; ch += j - i ) cout<< Hello!\n ; 27 output Hello! Hello! Hello!

The break and continue Statements Break Causes immediate exit from a while, for, do/while or switch structure Program execution continues with the first statement after the structure Common uses of the break statement: Escape early from a loop Skip the remainder of a switch structure Continue Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed In the for structure, the increment expression is executed, then the loop-continuation test is evaluated 28

Break Statement the break statement when executed in a while, for, do while, or switch structure, causes immediate exit from that structure. Note: If break comes in nested loops, it causes immediate, exit from the innermost- loop. Thus, it is used to escape early from a loop or to skip the remainder of a switch structure Example 1 i=1; while(true) { // endless condition, it is always true cout<<i; if(i==5) break; i++; } Output break: stop and exit the loop 1 2 3 4 5 29

Break Statement Example 2 for(x=1;x<=10;x++) { if(x==5) break; cout<<x; } Output exit before printing 5 1 2 3 4 Example 3 for(x=1;x<=10;x++) { cout<<x; if(x==5) break;} Output exit after printing 5 1 2 3 4 5 Note : making example 2 output same as example 1 30

Quiz Write program to Calculate the following arithmetic expression, but must a void dividing by Zero and the program must continue executing until the user decide to stop it. Solution #include<iostream.h> int x, y; char ans; int main( ) { do { cout<< Enter value of x: ; cin>>x; if(x==0) break; y=sqrt(fabs(x)+5)/x; cout<< y= <<y; break Statement cout<< would you like to enter more (y/n).? ; cin>>ans; } while(ans= Y ans= y ); return 0;} y = x x + 5 31

continue Statement The continue statement when executed in a while,for or do-while structure. Skip the remaining statement in body of the loop and proceeds with the next iteration of the loop Note In while and do while,the condition evaluated immediately after the continue statement is executed in for, the increment is executed first, then the condition is evaluated. Remark How continue affect the analogy between for and while Usually,while can be used to represent for. The one exception occurs when the increment in the while following the continue. In this case, the increment is not executed before the repetition condition is tested and the while does not execute in the same manner as the for. 32

continue Statement Example Lising continue statement for(x=1;x<=10;x++) { if(x==5) continue; cout<<x<< } continue prevented 5 to be printed Output 1 2 3 4 6 7 8 9 10 Implementing for using while(the exception case) x=1; While(x<=10) { if(x==5) continue; cout<<x<< ; x++;} Output continue goes direct to the condition (no increment) 1 2 3 4 33

continue Statement Example To enforce equivalence for for(x=1; x<=10; x++){ if(x == 5) continue; cout << x ; } while x=0; while (x <= 9){ x++; if( x == 5 ) continue; cout << x; } 34