LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Similar documents
LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

CHAPTER : 9 FLOW OF CONTROL

Lecture 6. Statements

REPETITION CONTROL STRUCTURE LOGO

DELHI PUBLIC SCHOOL TAPI

Programming Fundamentals

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Computer Programming

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

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.

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

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

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

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

The following expression causes a divide by zero error:

Type Conversion. and. Statements

UIC. C Programming Primer. Bharathidasan University

CHAPTER 9 FLOW OF CONTROL

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

Introduction. C provides two styles of flow control:

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

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

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

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

Sample Paper Class XI Subject Computer Sience UNIT TEST II

Chapter 4. Computation. Bjarne Stroustrup.

Computer Programming

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

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Computer Programming

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Programming for Electrical and Computer Engineers. Loops

Problem Solving and 'C' Programming

CS242 COMPUTER PROGRAMMING

C++ Programming Assignment 3

Creating a C++ Program

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

Flow Control. CSC215 Lecture

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

INTRODUCTION TO PROGRAMMING

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Computer Programming

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

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

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Chapter 4 Computation

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Computer Programming

COMPUTER SCIENCE (083)

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

5. Control Statements

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS

Introduction to Algorithms and Programming (COMP151)

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

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

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

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Operator overloading: extra examples

Score score < score < score < 65 Score < 50

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

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

Scientific Computing

Binary Tree Applications

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Week 2. Muhao Chen.

Pointers, Dynamic Data, and Reference Types

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

Programming, numerics and optimization

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

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

Chapter 4 - Notes Control Structures I (Selection)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

ECE G205 Fundamentals of Computer Engineering Fall Exercises in Preparation to the Midterm

do { statements } while (condition);

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

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

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

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

C++ Final Exam 2017/2018

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Name Section: M/W T/TH Number Definition Matching (8 Points)

Chapter 7 Functions. As an example, let us write some code to make a virtual cup of coffee.

Chapter 3 Problem Solving and the Computer

Functions. Introduction :

Name Section: M/W T/TH Number Definition Matching (6 Points)

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

Transcription:

Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Dr. Samaher Hussein Ali Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com

Control Structures Outline: The if Statement The switch Statement The while Statement The do Statement The for Statement The continue Statement The break Statement The goto Statement The return Statement Home works

The if Statement It is sometimes desirable to make the execution of a statement dependent upon a condition being satisfied. The if statement provides a way of expressing this, the general form of which is: if (expression) statement; First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise, nothing happens. For example, when dividing two values, we may want to check that the denominator is nonzero: if (count!= 0) average = sum / count; To make multiple statements dependent on the same condition, we can use a compound statement: if (balance > 0) interest = balance * creditrate; balance += interest; Dr. Samaher Hussein Ali Notes of Lecture 4

The if Statement

The if-else Statement A variant form of the if statement allows us to specify two alternative statements: one which is executed if a condition is satisfied and one which is executed if the condition is not satisfied. This is called the if-else statement and has the general form: if (expression) statement1; else statement2; First expression is evaluated. If the outcome is nonzero then statement1 is executed. Otherwise, statement2 is executed. For example: if (balance > 0) interest = balance * creditrate; balance += interest; else interest = balance * debitrate; balance += interest;

The if-else Statement

The if-else Statement Example: write the program to read two numbers, if the first number is greater than the second number test the ability of dive that number on 2 (i.e., the number is even) else print that number. While, if first number equal the second number print these numbers else find if the fist number accept dive on 3 then compute the multiplication first number on 3. # include <iostream.h> # include<conio.h> void main() int a; int b; int c; cout<< Enter the two numbers: <<endl; cin>>a>>b; if (a > b) if ((a % 2)==0) cout<< the number: <<a<< is even<<endl; else cout<< the number: <<a<< is odd<<endl;

The if Statement if (a==b) cout<< the two numbers: <<a<<b<<endl; Else if((a % 3)==0) c=a*3 cout<< the new number: <<c<<endl; getch(); )

The switch Statement The switch statement provides a way of choosing between a set of alternatives, based on the value of an expression. The general form of the switch statement is: switch (expression) case constant1: statements;... case constantn: statements; default: statements; First expression (called the switch tag) is evaluated, and the outcome is compared to each of the numeric constants (called case labels), in the order they appear, until a match is found. The statements following the matching case are then executed. Note the plural: each case may be followed by zero or more statements (not just one statement). Execution continues until either a break statement is encountered or all intervening statements until the end of the switch statement are executed. The final default case is optional and is exercised if none of the earlier cases provide a match.

The switch Statement Example: suppose we have parsed a binary arithmetic operation into its three components and stored these in variables operator, operand1, and operand2. The following switch statement performs the operation and stored the result in result. switch (operator) case '+': result = operand1 + operand2; case '-': result = operand1 - operand2; case '*': result = operand1 * operand2; case '/': result = operand1 / operand2; default: cout << "unknown operator: " << ch << '\n'; As illustrated by this example, it is usually necessary to include a break statement at the end of each case. The break terminates the switch statement by jumping to the very end of it.

The switch Statement It should be obvious that any switch statement can also be written as multiple if-else statements. The above statement, for example, may be written as: if (operator == '+') result = operand1 + operand2; else if (operator == '-') result = operand1 - operand2; else if (operator == '*') result = operand1 * operand2; else if (operator == '/') result = operand1 / operand2; else cout << "unknown operator: " << ch << '\n'; Note: However, the switch version is arguably neater in this case. In general, preference should be given to the switch version when possible. The if-else approach should be reserved for situation where a switch cannot do the job (e.g., when the conditions involved are not simple equality expressions, or when the case labels are not numeric constants).

The switch Statement Example: write the program to print the months of year. # include <iostream.h> # include<conio.h> void main() int x; switch (x) case 1: cout << Jan <<endl; case 2: cout << Feb <<endl; case 3: cout << Mar <<endl; case 4': cout << Apr <<endl;.. case 12': cout << Dec <<endl; default: cout << Error: " << endl; getch()

The while Statement The while statement (also called while loop) provides a way of repeating an statement while a condition holds. It is one of the three flavors of iteration in C++. The general form of the while statement is: while (expression) statement; First expression (called the loop condition) is evaluated. If the outcome is nonzero then statement (called the loop body) is executed and the whole process is repeated. Otherwise, the loop is terminated. For example, suppose we wish to calculate the sum of all numbers from 1 to some integer denoted by n. This can be expressed as: i = 1; sum = 0; while (i <= n) sum += i++; For n set to 5, the following Table provides a trace of the loop by listing the values of the variables involved and the loop condition.

The while Statement It is not unusual for a while loop to have an empty body (i.e., a null statement). The following loop, for example, sets n to its greatest odd factor. while (n % 2 == 0 && n /= 2) ; Here the loop condition provides all the necessary computation, so there is no real need for a body. The loop condition not only tests that n is even, it also divides n by two and ensures that the loop will terminate should n be zero.

The while Statement Example: write the program to print the sum of numbers from 1 to 100. # include <iostream.h> # include<conio.h> void main() int i; int sum; sum=0; i=1; while (i<=100) sum=sum+i ; i++; cout<< sum= <<sum<< endl; getch();

The Do Statement The do statement (also called do loop) is similar to the while statement, except that its body is executed first and then the loop condition is examined. The general form of the do statement is: do statement; while (expression); First statement is executed and then expression is evaluated. If the outcome of the latter is nonzero then the whole process is repeated. Otherwise, the loop is terminated. The do loop is less frequently used than the while loop. It is useful for situations where we need the loop body to be executed at least once, regardless of the loop condition. For example, suppose we wish to repeatedly read a value and print its square, and stop when the value is zero. This can be expressed as the following loop: do cin >> n; cout << n * n << endl; while (n!= 0); cout << n ^ 2 Note:- Unlike the while loop, the do loop is never used in situations where it would have a null body. Although a do loop with a null body would be equivalent to a similar while loop, the latter is always preferred for its superior readability.