Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.

Slides:



Advertisements
Similar presentations
1 CSE1301 Computer Programming Lecture 8 Selection.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
For loops For loops are controlled by a counter variable. for( c =init_value;c
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
1 CSE1301 Computer Programming Lecture 9 Selection.
1 CSE1301 Computer Programming Lecture 10: Iteration (Part 1)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
1 CSE1301 Computer Programming Lecture 10: Iteration (Part 1)
1 Chapter 3 Flow of Control. 2 Outline  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound statement.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Lecture 4: C/C++ Control Structures Computer Programming Control Structures Lecture No. 4.
IIT Kanpur C Course Lecture 3 Aug 31, Rishi Kumar, Final year BT-MT, CSE.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
6. LOOPS. Example: Summing a Series of Numbers #include int main(void) { int n, sum = 0; printf("This program sums a series of numbers.\n"); printf("Enter.
Engineering Computing I Chapter 3 Control Flow. Chapter 3 - Control Flow The control-flow of a language specify the order in which computations are performed.
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
The following statements are for y = -1; if ( x ) if ( x>0 ) y = 1; else y = 0; A. y= -1 x0 B. y= 0 x0 C. y= 1 x
Dale Roberts Program Control Department of Computer and Information Science, School of Science, IUPUI Fall 2003 CSCI 230 Dale Roberts, Lecturer
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
Chapter 5: Structured Programming
CSE 220 – C Programming Loops.
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
CSE1320 INTERMEDIATE PROGRAMMING Operators+Conditionals+Loop
INC 161 , CPE 100 Computer Programming
Looping.
- Additional C Statements
Structured Program
Chapter 4 - Program Control
Loops in C.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Program Control Topics While loop For loop Switch statement
CSI 121 Structure Programming Language Lecture 9 Selection
2.6 The if/else Selection Structure
Dale Roberts, Lecturer IUPUI
Introduction to Computing Lecture 04: Booleans & Selection
Control Statements Paritosh Srivastava.
Flow of Control.
CSC215 Lecture Control Flow.
CSCE 206 Lab Structured Programming in C
Presentation transcript:

Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

2 Topics Control Flow Statements The for Statement The while Statement The do while Statement The if Statement The if else Statement The else if Statement The break Statement The continue Statement The goto Statement The switch Statement

3 Control flow statements The logic of solving a problem forces the execution of program statements in a specific order, function of the state of the solving process. The control flow statements and expressions serve this purpose. –Loop statements: for, while, do –Conditional statements: if, if-else –Selection statements: switch –Unconditional jump statement: goto –Conditional expressions

4 The general form of a for statement is: for(expr1;expr2;expr3)statement; The for statement 1/2 Initialize Test Increment Body of the Loop Ex. N = 0 N <= 10 N++ printf(“ N = %d”,N) for(N = 0; N<=10; N++) printf(“ %d”, N); No semi-colon (;) Output:

5 The for statement may be used as: N=0; for( ; N<=10 ; ) { printf(“ %d”, N); N++; } The for statement 2/2 Initialize Test Increment semi-colons (;) are necessary Put braces if more than one statements in the for loop

6 Logic flow of a for statement: for(expr1;expr2;expr3)statement; next statement statement expr2 next statement expr1 expr3 00 0 Operation of the for Loop

7 Find even and odd numbers between 1 to 20 #include void main(void){ int X,Y; for(X=0;X<=2;X++){ printf(“\n”); for(Y=X;Y<=20;Y+=2) printf("%d",Y); } Using for Output

8 Implements the repetition in an algorithm Repeatedly executes a block of statements Tests a condition (Boolean expression) at the start of each iteration Terminates when condition becomes false (zero) The while statement 1/4

9 The general form of a while statement is: while(expression) statement; Test Body of the Loop Ex. getche() == ‘a’ printf(“This character is a”) while(getche() == ‘a’) printf(“This character is a”) No semi-colon (;) The while statement 2/4

10 The while statement may be used as: N=0; while(N<=10) { printf(“ %d”, N); N++; } The while statement 3/4 Initialize Test Increment No semi-colons (;) Put braces if more than one statements in the while loop

11 Common Mistakes in while is extra semi-colon. N=0; while(N<=10); { printf(“ %d”, N); N++; } The while statement 4/4 Semi-colon marks the end of the while-block -- usual cause of infinite loops

12 Logic flow of a while statement: while(expression) statement; next statement Operation of the while Loop statement expression 00 next statement 0

13 Count characters in a pharase typed in #include void main(void){ int count=0; printf(”Type a character:”); while(getche() != ‘\r’); count++;} printf(”\n character count is: %d",count); } Using while Output arthdfi character count is: 7 Press Enter

14 The general form of a for statement is: for(expr1;expr2;expr3)statement; next statement The while statement: expr1; while(expr2){ statement expr3; } next statement Structure of The for and The while statements statement expr2 next statement expr1 expr3 00 0

15 The general form of a do statement is: do statement while(expression); Test Body of the Loop Ex. printf(“N = %d”, N) N <= 10 N++ do { printf(“N = %d”, N); N++; } while(N<=10); No semi-colon (;) The do while statement 1/3

16 The do while statement may be used as: N=0; do { printf(“ %d”, N); N++; } while(N<=10); The do while statement 2/3 Initialize Test Increment No semi-colons (;) Put braces if more than one statements in the do while loop semi-colon (;)

17 The do while statement 3/3 Increment The do while statement may be used as: N=0; do { printf(“ %d”, N); N++; } while(N<=10); IMPORTANT!! The increment is performed AFTER the body of the loop

18 The general form of a do statement is: do statement while(expression); next statement Operation of the do while Loop statement expression 00 next statement 0

19 Determines whether a block is executed. Implements the selection instructions within an algorithm. Decides what to do by evaluating a Boolean expression. If the expression is true (non-zero), the block is executed. The if statement 1/5

20 The general form of an if statement is: if (expression) statement; next statement If the expression evaluates to a nonzero value the statement is executed and then the control passes to the next statement. If the expression evaluates to a zero value the statement is skipped and the control passes directly to the next statement. The if statement 2/5

21 Common mistake if (number % 2 != 0); { printf("%d is an odd ", number); } printf("number\n"); The if statement 3/5 Do not put semicolon here!

22 Common mistake if (number % 2 = 0) { printf("%d is an odd ", number); } printf("number\n"); The if statement 4/5 Should be ==

23 Common mistake if (number % 2 == 0) { printf("%d is an odd ", number); } printf("number\n"); The if statement 5/5 Do not put “then” here!

24 /* Read in a number, and echo it if it is odd. */ #include void main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number % 2 != 0) { printf("%d\n", number); } Example

25 Which of the following code fragments are equivalent? if (number % 2 != 0) { printf("%d", number); } printf(” is odd\n"); if (number % 2 != 0) printf("%d", number); printf(” is odd\n"); if (number % 2 != 0) { printf("%d", number); printf(” is odd\n"); } A B C Exercise 1/2

26 A and B are equivalent? if (number % 2 != 0) { printf("%d", number); } printf(” is odd\n"); if (number % 2 != 0) printf("%d", number); printf(” is odd\n"); if (number % 2 != 0) { printf("%d", number); printf(” is odd\n"); } A B C Exercise 2/2

If-else statement The general form of an if-else statement is: if (expression) statement1; else statement2; next statement If the expression evaluates to a nonzero value the statement1 is executed and then the control passes to the next statement. If the expression evaluates to a zero value the statement1 is skipped, statement2 is executed and then the control passes to the next statement.

If there are several successive if statements followed by an else part then the else part is paired with the closest if statement. if (expression 1 ) statement 1 ; if (expression 2 ) statement 2 ;... if (expression n ) statement n ; else statement n+1 ; Dangling else problem No semicolons here!

29 /* Determine whether an input number is odd or even. */ #include main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number % 2 != 0) { printf("%d is an odd number\n", number); } else { printf("%d is an even number\n", number); } Example: if else

Find the minimum number out of three given integers X,Y and Z. #include void main(void){ int X,Y,Z,min; scanf("%d%d%d",&X,&Y,&Z); if(X < Y && X < Z) min=X; else if(Y < X && Y < Z) min=Y else min=Z; printf("min=%d\n",min); } Using else if Nested if-else

31 if (ch >= ’a’ && ch <= ’z’) { printf(“%c is in lower case.\n”, ch); } else if (ch >= ’A’ && ch <= ’Z’) { printf(“%c is in upper case.\n”. ch); } else if (ch >= ’0’ && ch <= ’9’) { printf(“%c is a digit with value %d.\n”, ch, ch - ’0’); } Example: else if

32 Multiple alternative blocks each with a Boolean expression. First expression which evaluates to true causes execution of the associated block. Only at most one block will be executed. Nested if statement

The execution of a cycle statement (while, do, for) can be terminated unconditionally using the statement break Break terminates the innermost cycle that contains it and the control passes to the statement following the cycle. while(expr1){ statements1 if(expr2)break; statements2 } next statement The break statement expr2  0

Read floating-point numbers from standard input: –For each number X > 0 compute log 10 (X) –Terminate the program when X <= 0. #include void main(void){ double X; while(1){ printf(”Enter a number"); scanf("%f",&X); if(X <= 0) break; printf("log10(%f)=%f\n",X,log10(X)); } Using break Exit the cycle “while (True)” infinite loop

The execution of a cycle statement (while, do, for) can be continued skipping part of the cycle body using the statement continue The following sequences are equivalent. The continue statement while(expr1){ statements1 if(expr2)continue; statements2 } next statement while(expr1){ statements1 if(expr2==0){ statements2 } next statement

Print all numbers from 1 to 10 except 5. #include void main(void){ int X; while(x =1; x <= 10; x++){ if(X == 5) continue; printf("%d",x); } Using continue Continue cycle without printing 5

The goto statement The format of the goto statement is goto label where label is an identifier. The goto statement performs an unconditional jump to a labeled statement. The program continues from that statement. A labeled statement has the form: label: statement The goto statement is useful for exiting at once several nested control statements (while, do, case, if) or when it is necessary to continue processing from a "remote" part of the currently executing function.

The goto statement is considered harmful according to the standards of modern programming methodology. If used carelessly it can undermine the clear program structure provided by other structured control-flow statements. The goto statement must be used only when other control statements would lead to a complex program structure. Warning

39 The switch Statement 1/2 The switch statement is similar to the else-if construct. If break statement is not used following a case, control will fall through to the next case. Switch variable is integer or character variable or expression. Floating point number is not used.

40 Structure of the switch statement: switch(op) { case ‘a’: statement; break; default: statement; } Integer or character variable or expression Integer or character constant Statements are executed if switch variable op = ‘a’ Statements are executed if no other case applies The switch Statement 2/2

41 switch(op) { case ‘+’: printf(“%f”, N1+N2); break; case ‘-’: printf(“%f”, N1-N2); break; default: printf(“ neither + nor - operator”) ; } Example: switch statement

#include void main() { float mark; printf("What is your mark? "); scanf("%f", &mark); if (mark < 50) { printf("Sorry. You failed.\n"); } else { printf("Yey! You passed!\n"); } Complete Example Declares that mark is a variable which can contain a floating point number Outputs a “prompt” so the user knows what the program wants. Inputs the floating point content of the variable mark. (Note: ampersand!) This block of instructions is performed if the comparison is true. This block of instructions is performed if the comparison is false.