LAB 5: REPETITION STRUCTURE(LOOP)

Similar documents
LAB 5: REPETITION STRUCTURE(LOOP)

LAB 2 INTRODUCTION TO PROGRAMMING

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

Lab 2: Structured Program Development in C

Dept. of CSE, IIT KGP

Condition Controlled Loops. Introduction to Programming - Python

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

Loops / Repetition Statements

Control Structure: Loop

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

A Look Back at Arithmetic Operators: the Increment and Decrement

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

Computer Programming. Decision Making (2) Loops

3 The L oop Control Structure

Structured Program Development

REPETITION CONTROL STRUCTURE LOGO

Flow Chart. The diagrammatic representation shows a solution to a given problem.

CS1100 Introduction to Programming

ECET 264 C Programming Language with Applications. C Program Control

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

Lab ACN : C++ Programming Exercises

Structured Program Development in C

Structured Programming. Dr. Mohamed Khedr Lecture 9

Arrays and Strings. Arash Rafiey. September 12, 2017

Control Structures II. Repetition (Loops)

Repetition and Loop Statements Chapter 5

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

Prepared by: Shraddha Modi

Special Section: Building Your Own Compiler

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

AMCAT Automata Coding Sample Questions And Answers

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

Unit 3. Operators. School of Science and Technology INTRODUCTION

IT 1033: Fundamentals of Programming Loops

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Programming for Engineers Introduction to C

Chapter 3 Structured Program Development

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

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

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

Functions. Arash Rafiey. September 26, 2017

Chapter 4: Control structures. Repetition

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

Chapter 5: Control Structures

Operators & Expressions

PROGRAMMING IN C AND C++:

Add Subtract Multiply Divide

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

Control Statements: Part 1

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

Control structure: Repetition - Part 2

Chapter 4: Control structures

LAB 1 Binary Numbers/ Introduction to C. Rajesh Rajamani. ME 4231 Department of Mechanical Engineering University Of Minnesota

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Any Integer Can Be Written as a Fraction

Lecture 7 Tao Wang 1

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

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

C: How to Program. Week /Mar/05

Assignment: 1. (Unit-1 Flowchart and Algorithm)

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Computer Science & Engineering 150A Problem Solving Using Computers

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

Introduction to Java Applications

Condition Controlled Loops. Introduction to Programming - Python

Control Statements. Musa M. Ameen Computer Engineering Dept.

In this chapter you ll learn:

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

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

Chapter 2 - Introduction to C Programming

Full file at C How to Program, 6/e Multiple Choice Test Bank

Decision Making and Loops

Chapter 4 C Program Control

Full file at

11.3 Function Prototypes

Introduction. C provides two styles of flow control:

LESSON 3 CONTROL STRUCTURES

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

Loops (while and for)

Problem Solving and 'C' Programming

r } ~ ~ ~.,-~_.-.,..--- ~.._ ~ -.- " ~.., ~ i-~--~-..., _-_... 4 _-~ _. '".~ j l.- ~ i...l...i- ~.JI

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

Repetition Structures

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

CS 108 Computing Fundamentals. October/November Array Bootcamp

Programming for Engineers Iteration

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

Principles of Programming. Chapter 6: Arrays

Prepared by: Shraddha Modi

Computer Programming C++ (wg) CCOs

Repetition, Looping CS101

Lesson 9: Decimal Expansions of Fractions, Part 1

LAB 2.1 INTRODUCTION TO C PROGRAMMING

Introduction to Computer Science Midterm 3 Fall, Points

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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 ).

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

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

Transcription:

LAB 5: REPETITION STRUCTURE(LOOP) OBJECTIVES 1. To introduce two means of repetition/loop structures; counter-controlled and sentinelcontrolled. 2. To introduce the repetition structures; for, while, do-while and nested loops statements. 3. To analyze and identify a control variable in a test condition. 4. To analyze and apply repetition structures as program control in writing C program. NOTES 1. Generally there are two means of repetition/loop structure. They are: i. Counter-controlled ii. Sentinel-controlled 2. Counter-controlled repetition is also called definite repetition because we know in advance how many times the loop will be executed. Flowchart of a counter-controlled loop is generally described as follows: 3. Sentinel-controlled repetition is also called indefinite repetition because it is not known in advance how many times the loop will be executed. Flowchart of a sentinel-controlled loop is generally described as follows:

4. There are differences in syntax among for, while and do-while loop structure: i. The syntax for for loop is described below: for (counter init; end condition; increment statement) statement; statement; ii. The syntax and flowchart for while loop is described below: while (condition) statement; statement; iii. The syntax and flowchart for do-while loop are as below: do statement; statement; while(condition); 5. Coding examples to implement counter-controlled in for, while or do-while loop are described in Table 4a. Coding examples to implement sentinel-controlled in for, while or do-while loop are described in Table 4b.

Table 4a: Counter-controlled loop WHILE DO.. WHILE FOR #include <stdio.h> int main() #include <stdio.h> int main() #include <stdio.h> int main() int i=1;//set the counter float mark; while (i <= 5) printf("\nenter marks %d:",i); scanf("%f",&mark); printf("\nthe mark entered %.2f",mark); i=i+1;//update counter printf("\n\n"); return 0; int i=1;//set the counter float mark; do printf("\nenter marks %d:",i); scanf("%f",&mark); printf("\nthe mark entered %.2f",mark); i=i+1;//update counter while (i <= 5); printf("\n\n"); return 0; int i; float mark; for (i=1;i<=5;i++) printf("\nenter marks %d:",i); scanf("%f",&mark); printf("\nthe mark entered %.2f",mark); printf("\n\n"); return 0;

Table 4b: Sentinel-controlled loop WHILE DO.. WHILE #include <stdio.h> void main() int i=1;//set the initial value float mark; while (i!= 999) printf("\nenter marks : "); scanf("%f",&mark); printf("\nthe mark entered %.2f",mark); printf("\nenter 999 if you want to stop, otherwise enter any number but not 999 : "); scanf("%d",&i); printf("\n\n"); #include <stdio.h> void main() int i=1;//set the initial value float mark; do printf("\nenter marks : "); scanf("%f",&mark); printf("\nthe mark entered %.2f",mark); printf("\n\nenter 999 if you want to stop, otherwise enter any number but not 999 : "); scanf("%d",&i); while (i!= 999); printf("\n\n");

LAB EXERCISES EXERCISE 1: CONCEPT UNDERSTANDING 1. Test condition for a selection or loop structure can be (similar/dissimilar). However, they can be distinguished by flow of arrow described in a flowchart. 2. for loop is suitable to be implemented as. 3. do-while loop is executed. 4. If we did not know in-advance how many times we want to repeat, then a loop is suitable. 5. If an infinite loop is encountered during program execution, this means that the loop s body does not contain condition. 6. The expression in or statement can be written as counter-controlled or sentinel-controlled loop. 7. loop is performed first in a nested repetition structure. 8. A is part of a test condition to decide whether the loop continues or stops. EXERCISE 2- DISPLAYING OUTPUT, ERRORS TRACING AND RE-WRITING CODE FRAGMENTS 1. Analyze and identify syntax and/or logic errors from these code fragments. Then, attempt to correct the errors. i. Coding repeat ten times and print each of the loop counter in a new line. for(i=1;i<10;i--) printf( %d, counter); printf( \n ); ii. Coding repeat five times and calculate the sum of the loop counter.

while(counter<5) sum=sum+counter; counter++; iii. Coding repeat five times and print the sum of each step in a loop. do counter=1; counter++; sum=sum+counter; printf( Sum=%d,sum); while(counter<5) iv. Sum up number while it is not 999. while(number == 999) sum=sum+number; number++; v. Reading and displaying number stops when you no longer need it. do printf( Enter number : ); scanf( %d, &number); printf( Number : %d\n, number); while(choice!= y )

2. Analyze the program in Figure 1 and produce output from the program run. #include <stdio.h> int main () int x = 1, total = 0, y; while ( x <= 4) y = x * x + 2; printf ( %d\n, y); total += y; ++x; printf ( Total is %d\n, total); return 0; Figure 1 3. Analyze the program segment in Figure 2 and produce output from the program run. for (i = 1; i <= 2; i++) for (j = 1; j <= 3; j++) for (k = 1; k <= 4; k++) printf ( * ); printf ( \n ); printf ( \n ); Figure 2

4. Rewrite the code segment in Figure 3 using a while statement. int n; int m = 5; for(n = 1;n <= 6;n++) printf( %d\n, m); m = m + 3; Figure 3 EXERCISE 3-PROBLEM SOLVING 1. Determine and state control variable(s) from this stated problems. i. Program finds and prints average of three test scores, then asks whether user wants to continue. ii. Program repeats for ten times to sum up the numbers. iii. Continue reading when you decided to enter y to indicate a yes.

iv. Total up numbers while it is not -999. v. Draw pattern for five rows and three columns. vi. This C program is to find the largest number of a series of numbers entered (use these numbers as your test data): 33, 10, 40, 30, 22, 29, 50, 69, 40, 67. vii. Construction engineers use concrete to build high-rise buildings. Since concrete nearly is incapable of resisting tension loads, reinforcing steel, known as rebar, is embedded in concrete to resist tension. The bar is available in a number of sizes. Table 4c shows the ASTM (American Society for Testing and Materials) standard reinforcing bars size, weight, and diameter: Table 4c Size Weight (lb./ft.) Diameter (in.) 2 0.167 0.250 3 0.376 0.375 4 0.668 0.500 5 1.043 0.625 6 0.444 0.555 This C program is to calculate the total weight of the rebar for 5 sets of data by input value of rebar size and length. 2. Write a C program that creates a table of degrees Celcius with the corresponding degrees Fahrenheit. Begin at 0 0 C and proceed to 100 0 C in 20 0 C increments using a suitable repetition structure. The sample output is described in Table 4d. Produce a flowchart before attempting to write the coding. Given, F = C * (9/5) + 32 where F is Fahrenheit, in degrees, and C is Celcius, in degrees.

Table 4d ---------------------------------------------------------- Table of Celcius and Fahrenheit degrees Degrees Degrees Celcius Fahrenheit --------------------------------------------------------- 0.00 32.00 20.00 68.00 40.00 104.00 60.00 140.00 80.00 176.00 100.00 212.00 3. Write a C program that reverses the digits of a number. The number of digits to be entered is unlimited. Hint: Use division and modulus operator. The process of reversing the digits is not possible if the entered number is 0. Produce a flowchart before attempting to write the coding. The sample output is shown below. Sample output: Enter number to be reversed : 13579 Reversed number : 97531 4. Design and write a C program that reads n integer values less than 100 and then determines and outputs whether the sequence entered is sorted in ascending order, descending order, or is unordered. Requirements: i. Specifically, in the first prompt for the first integer, you must have 1st, in the second 2nd, and in the third 3rd. After the third, you can use an integer followed by suffix th, as in 4th. ii. Special cases: 11, 12 and 13 should be written as 11th, 12th and 13th and NOT 11st, 12nd and 13rd. Produce a flowchart before attempting to write the coding. The sample output is shown below. Sample output1: How many integers do you have? 4 Enter the 1st integer: 10 Enter the 2nd integer: 8 Enter the 3rd integer: 6 Enter the 4th integer: 4 Your sequence is sorted in descending order Sample output2: How many integers do you have? 4 Enter the 1st integer: 1 Enter the 2nd integer: 1 Enter the 3rd integer: 2 Enter the 4th integer: 2 Your sequence is sorted in ascending order

Sample output3: How many integers do you have? 4 Enter the 1st integer: 2 Enter the 2nd integer: 3 Enter the 3rd integer: 1 Enter the 4th integer: 4 Your sequence is unordered Sample output4: How many integers do you have? 21 Enter the 1st integer: 1 Enter the 2nd integer: 2 Enter the 3rd integer: 3 Enter the 4th integer: 4 Enter the 5th integer: 5 Enter the 6th integer: 6 Enter the 7th integer: 7 Enter the 8th integer: 7 Enter the 9th integer: 8 Enter the 10th integer: 8 Enter the 11th integer: 9 Enter the 12th integer: 9 Enter the 13th integer: 9 Enter the 14th integer: 9 Enter the 15th integer: 9 Enter the 16th integer: 9 Enter the 17th integer: 9 Enter the 18th integer: 9 Enter the 19th integer: 9 Enter the 20th integer: 9 Enter the 21st integer: 0 Your sequence is unordered. 5. A positive integer p is a prime number if it is not evenly divisible by any other integers, other than 1 and itself. The first prime integer is defined to be 2. The next prime is 3, since it is not evenly divisible by any integers other than 1 and 3; and 4 is not prime because it is evenly divisible by 2. Write a C program to generate all prime numbers up to 50. Hint: Test integer p for divisibility by all integers from 2 through p-1. If any such integer evenly divided p, then p would not be prime; otherwise, it would be a prime number. Sample output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

6. Write a C program that acts as simple printing calculator. The program should allow the user to type in expressions of the form number operator The following operators should be recognized by the program: + - * / S E The S operator tells the program to set the accumulator to the typed-in number. The E operator tells the program that execution is to end. The arithmetic operations are performed on the contents of the accumulator with the number that was keyed in acting as the second operand. The following is a sample run showing how the program should operate. Begins Calculations 10 S Set Accumulator to 10 = 10.000000 Contents of Accumulator 2 / Divide by 2 = 5.000000 Contents of Accumulator 55 - Subtract 55 = -50.000000 100.25 S Set Accumulator to 100.25 =100.250000 4 * Multiply by 4 =401.000000 0 E End of program End of Calculations. Make sure that the program detects division by zero and also checks for unknown operators. 7. A group of researchers implement the following decision table that relates loudness in decibels to human perception. Your program must also consider if an invalid input is entered when user decides to continue or stop from the loop. Sample output : Loudness (db) Perception < 50 Quite 51-70 Intrusive 71-90 Annoying 91-110 Very annoying > 110 Uncomfortable Please input the decibel scale: 50 Quite Do you want to continue? y Please input the decibel Scale: 90

Annoying Do you want to continue? 6 Invalid selection. You input a number. Do you want to continue? N 8. Write a C program that uses a loop and decision structure to determine whether a number is odd or even and total of each category. The program continues repetition when user enter Y or y ; otherwise it stops. An even number resulted a remainder of zero when it is divided by 2. Sample output: Enter a number to decide even or odd number: 6 6 is an even number Do you want to continue? y-yes other characters-no y Enter a number to decide even or odd number: 76 76 is an even number Do you want to continue? y-yes other characters-no y Enter a number to decide even or odd number: 991 991 is an odd number Do you want to continue? y-yes other characters-no n Number of even numbers: 2 Number of odd numbers: 1