Loops / Repetition Statements

Similar documents
Loops / Repetition Statements

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Decision Making and Loops

Subject: PIC Chapter 2.

Structured Programming. Dr. Mohamed Khedr Lecture 9

DECISION CONTROL AND LOOPING STATEMENTS

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

Dept. of CSE, IIT KGP

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

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Unit 3 Decision making, Looping and Arrays

Repetition and Loop Statements Chapter 5

Prepared by: Shraddha Modi

Chapter 4: Control structures. Repetition

MODULE 2: Branching and Looping

Loops (while and for)

Chapter 4: Control structures

C 101. Davide Vernizzi. April 29, 2011

For Loop. Variations on Format & Specific Examples

3 The L oop Control Structure

STUDENT LESSON A12 Iterations

Lecture 10. Daily Puzzle

Module 4: Decision-making and forming loops

Lab 2: Structured Program Development in C

Questions Bank. 14) State any four advantages of using flow-chart

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

Fundamentals of Programming Session 13

REPETITION CONTROL STRUCTURE LOGO

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CS1100 Introduction to Programming

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

A Look Back at Arithmetic Operators: the Increment and Decrement

CS1004: Intro to CS in Java, Spring 2005

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

EK131 E5 Introduction to Engineering

Flow Control. CSC215 Lecture

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

LOOPS. 1- Write a program that prompts user to enter an integer N and determines and prints the sum of cubes from 5 to N (i.e. sum of 5 3 to N 3 ).

Chapter 4. Flow of Control

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

(Refer Slide Time: 00:26)

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. What s Wrong with Fahrenheit/Celsius Program? One More Type of Control Flow

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Introduction. C provides two styles of flow control:

Repetition Algorithms

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

fifth Solutions to Exercises 85

Programming for Engineers Iteration

CMSC 104 -Lecture 9 John Y. Park, adapted by C Grasso

Repetition Structures II

Control Structure: Loop

Chapter 5: Control Structures

C: How to Program. Week /Apr/16

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Decision Making -Branching. Class Incharge: S. Sasirekha

Information Science 1

Information Science 1

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Why Is Repetition Needed?

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

CPE 101 slides adapted from UW course. Overview. Chapter UW CSE H1-1. An Old Friend: Fahrenheit to Celsius. Concepts this lecture

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

Chapter 8 Algorithms 1

CS110D: PROGRAMMING LANGUAGE I

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

Conditionals and Loops

Top-Down Program Development

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

EC 413 Computer Organization

C Functions. Object created and destroyed within its block auto: default for local variables

Chapter 5: Control Structures II (Repetition)

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

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

Lecture 5 Tao Wang 1

1. Basics 1. Write a program to add any two-given integer. Algorithm Code 2. Write a program to calculate the volume of a given sphere Formula Code

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

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

Computer Programming. Decision Making (2) Loops

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Iteration statements - Loops

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Problem Solving and 'C' Programming

Flow of Control: Loops

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Computer Science & Engineering 150A Problem Solving Using Computers

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

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Transcription:

Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for loop the do loop The programmer should choose the right kind of loop for the situation

Example 1: Fixing Bad Keyboard Input Write a program that refuses to accept a negative number as an input. The program must keep asking the user to enter a value until he/she enters a positive number. How can we do this?

Example 2: Grade of several students Write a program that continuously calculates the grade of all students marks and stop when the user wants. After calculating one student s grade (from his marks) the program must keep asking the user whether he likes to continue or not. How can we do this?

while Loop যত ন while য দ if ( condition ) statement; if condition is satisfied execute the statement(s) while condition is satisfied execute the statement(s)

Logic of an if statement condition evaluated true false statement

if logic Logic of a while Loop The while Loop condition evaluated condition evaluated true false true false statement statement

The while Statement formally A while statement has the following syntax: while ( condition ) statement; while ( condition ){ statement1; statement2; If the condition is true, the statement or a block of statements is executed Then the condition is evaluated again, and if it is still true, the statement/block is executed again The statement/block is executed repeatedly until the condition becomes false

The while Statement Example program that continuously asks for positive number as input: int n; printf ( Please enter a positive number: ); printf ( Please enter a positive number: ); scanf( %d,&n); while (n < 0){ printf ( Enter positive number, BE POSITIVE!\n ); scanf( %d, &n);

Some examples Print The sky is the limit! 10 times. main(){

Some examples Print The sky is the limit! 10 times. main(){

Some examples Print The sky is the limit! 100 times. main(){

Some examples Print The sky is the limit! n times. n will be user input int count = 1; while (count <= n) { count++; If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

Some examples Print first n numbers. Print odd numbers up to n. Print even numbers up to n. Print summation of first n numbers. Print summation of all odd numbers up to n. Print summation of all even numbers up to n. Print factorial of n Print x n, where x and n are integers.

Summary of a while statement A while loop is functionally equivalent to the following structure: initialization; while ( condition ) { statement; increment;

initialization; while ( condition ) { statement; increment; A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

Logic of a for loop for ( initialization ; condition ; increment ) statement; initialization condition evaluated false true statement increment

The for Statement An example of a for loop: for (count=1; count <= 5; count++) printf ( %d\n, count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

The for Statement The increment section can perform any calculation int num; for (num=100; num > 0; num -= 5) printf ( %d\n, num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

Some example problems Write down a program to find the summation of the following series: 1 2 3 4... 2 2 2 2 2 1 2 3 4...up to n Show all factors of a number n up to n Show smallest factor of a number n (other than 1) Show largest factor of a number n (other than itself) Prime number testing Perfect number testing GCD of two numbers * Normal way * Efficient way gcd(a,b) = gcd (b,a%b) if b > 0 Fibonacci series

The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed

Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

Infinite Loops An example of an infinite loop: int count = 1; while (1 == 1){ printf ( %d\n, count); count = count - 1; int count = 1; for(; ;){ printf ( %d\n, count); count = count - 1; This loop will continue executing until interrupted (Control-C) or until an underflow error occurs

The do Statement A do statement has the following syntax: do{ statement; while ( condition ); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

Logic of a do-while Loop statement true condition evaluated false

The do Statement An example of a do loop: int count = 1; do{ printf( %d\n, count); count++; while (count <= 5); The body of a do loop is executed at least once

The do Statement An example of a do loop: int n; do{ printf( Enter a positive number: ); scanf( %d,&n); while (n < 0); The body of a do loop is executed at least once

Comparing while and do The while Loop The do Loop condition evaluated true statement true statement false condition evaluated false

Example: Printing reverse of a number Write down a program that prints the digits of a number in reverse. For example: input: 6457 output: 7546 scanf( %d,&n); do{ a = n%10; printf( %d,a); n = n/10; while (n!= 0);

Relevant Problem: counting number of digits of a number Write down a program that prints number of digits of a number n. For example: input: 6457 output: 4 scanf( %d,&n); C = 0; do{ n = n/10; c++; while (n!= 0); printf( %d,c);

Nested Loops

Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop For each iteration of the outer loop, the inner loop iterates completely

What will the output? Nested Loops for(i=1; i <= 3; i++){ for(j=1; j <= 2; j++){ printf( Sky is the limit\n ); printf( The world is becoming smaller\n );

Output for(i=1; i <= 3; i++){ for(j=1; j <= 2; j++){ printf( Sky is the limit\n ); printf( The world is becoming smaller\n ); Sky is the limit Sky is the limit The world is becoming smaller

Output for(i=1; i <= 3; i++){ for(j=1; j <= 2; j++){ printf( Sky is the limit\n ); printf( The world is becoming smaller\n ); Sky is the limit Sky is the limit The world is becoming smaller Sky is the limit Sky is the limit The world is becoming smaller

Output for(i=1; i <= 3; i++){ for(j=1; j <= 2; j++){ printf( Sky is the limit\n ); printf( The world is becoming smaller\n ); Sky is the limit Sky is the limit The world is becoming smaller Sky is the limit Sky is the limit The world is becoming smaller Sky is the limit Sky is the limit The world is becoming smaller

Output for(i=1; i <= 3; i++){ for(j=1; j <= 2; j++){ printf( %d %d\n,i,j); 1 1 1 2 2 1 2 2 3 1 3 2

Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { printf ("Here \n"); count2++; count1++; 10 * 20 = 200

Analogy for Nested Loops Inner Loop Outer Loop

Some more Examples Write a program that prints all prime numbers up to x. The integer x will be input to your program. Write a program that prints all perfect numbers up to x. The integer x will be input to your program. Write a program that prints all prime factors of a number x given as input. Write down a program that will take an integer x as input and will count and print the number of prime numbers up to x. Write down a program that will take an integer n as input and will count and print the number of fibonacci numbers up to x.

Example: Stars Write a program that prints the following. The total number of lines will be input to your program. * ** *** **** ***** ****** ******* ******** ********* **********

Example: Stars Write a program that prints the following. The total number of lines will be input to your program. * ** *** **** ***** ****** ******* ******** ********* **********