advanced programming loop. 2 while repetition structure repetition structure –an action is to be...

39
Advanced Programming LOOP LOOP

Upload: phebe-austin

Post on 29-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Advanced Programming

LOOPLOOP

Page 2: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

2

while Repetition Structure

• Repetition Structure

– An action is to be repeated

• Continues while statement is true

• Ends when statement is false

– Contain either a line or a body of code

• Must alter conditional

– Endless loop

Page 3: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

A deceptive problem...

• Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas.

For example, the call:printNumbers(5)

should print:1, 2, 3, 4, 5

Page 4: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Find output

n = 5; j = 1; while ( j < 4 ) { if ( n >= 10 ) n = n – 2; else n = n * j; j++; } console.writeline( “ The n is ” + n);

Page 5: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

5

Example

write a program that reads in the grades of 50

students in a course (out of 100 points each )

and then count the number of A students

( grade > 85 ) and the number of B students

(grade > 75 ). And print the average grad

for all students.

Page 6: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

// Class average with counter-controlled repetition.

using System;

class Average1

{

static void Main( string[] args )

{

int total, // sum of grades

gradeCounter, // number of grades entered

gradeValue, // grade value

average; // average of all grades

total = 0; // clear total

gradeCounter = 1; // prepare to loop

while ( gradeCounter <= 10 ) // loop 10 times

{

Page 7: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Console.Write( "Enter integer grade: " );

gradeValue = Int32.Parse( Console.ReadLine() );

total = total + gradeValue;

gradeCounter = gradeCounter + 1;

}

average = total / 10; // integer division

Console.WriteLine( "\nClass average is {0}", average );

} // end Main

} // end class Average1

Page 8: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

8

Example

• Assume you put 1000 pounds in a projects

that returns a profit of about 5% per year.

How long will it take for your money to

double ?

• Assume you put 5000 pounds in a projects

that returns a profit of about 10% per year.

How much money will you have in 5 years

Page 9: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Find output

prod = 1;do {

prod = prod * m ;m = m + 1 ;

}while ( m < 6 ) ;console.writeline(“ prod is “+ prod ) ;

Page 10: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

10

for Repetition Structure

for ( int counter = 1; counter <= 5; counter++ )

Initial value of control variable Increment of control variable

Control variable name Final value of control variablefor keyword

Loop-continuation condition

Page 11: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

// Counter-controlled repetition with the for structure.

using System;

class ForCounter {

static void Main( string[] args ) {

for ( int counter = 1; counter <= 5; counter++ )

Console.WriteLine( counter +” “);

}

}

Page 12: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Examples Using the for Statement

– Vary control variable from 1 to 100 in increments of 1• for ( int i = 1; i <= 100; i++ )

– Vary control variable from 100 to 1 in increments of -1• for ( int i = 100; i >= 1; i-- )

– Vary control variable from 7 to 77 in steps of 7• for ( int i = 7; i <= 77; i += 7 )

– Vary control variable from 20 to 2 in steps of -2• for ( int i = 20; i >= 2; i -= 2 )

– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20• for ( int i = 2; i <= 20; i += 3 )

– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0• for ( int i = 99; i >= 0; i -= 11 )

Page 13: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Loop tables

• What statement in the body would cause the loop to print:2 7 12 17 22

• To see patterns, make a table of count and the numbers.– Each time count goes up by 1, the number should go up by 5.

– But count * 5 is too great by 3, so we subtract 3.

count number to print 5 * count

1 2 5

2 7 10

3 12 15

4 17 20

5 22 25

5 * count - 3

2

7

12

17

22

Page 14: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Loop tables question

• What statement in the body would cause the loop to print:17 13 9 5 1

• Let's create the loop table together.– Each time count goes up 1, the number printed should ...

– But this multiple is off by a margin of ...

count number to print

1 17

2 13

3 9

4 5

5 1

-4 * count -4 * count + 21

-4 17

-8 13

-12 9

-16 5

-20 1

-4 * count

-4

-8

-12

-16

-20

Page 15: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

15

Example

Write a program to display all the numbers

divisible by 5 in the range 0 to 5000.

Page 16: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

16

Example

Write a program to ask the user for a

positive integer, and then display its

factorial. Given that

factorial(n) is 1 X 2 X 3 …… x n 

Page 17: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

using System;

using System.Windows.Forms;

class Interest

{

static void Main( string[] args )

{

double amount, principal = 1000.00, rate = .05;

string output;

output = "Year\tAmount on deposit\n";

for ( int year = 1; year <= 10; year++ )

{

amount = principal *Math.Pow( 1.0 + rate, year );

output += year + "\t" +

String.Format( "{0:C}", amount ) + "\n";

}

MessageBox.Show( output, "Compound Interest",

MessageBoxButtons.OK, MessageBoxIcon.Information );}}

Page 18: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

18

for ( m=1 ; m<=9 ; m=m+2 )

{

x = pow ( m , 2 );

console.writeline(m +” “+ x );

}

Find the output

Page 19: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• Write a C program that reads in 30 integer numbers and then print out their sum and average

Page 20: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Example

• Write a program that does a survey on a certain question. The question has four possible answers. Run the survey on 20 people and then display the number of people who chose each answer.

• Example:

What is your favorite subject?

A. Mathematics

B. Economics

C. Programming

D. Physics

Page 21: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Example

• write a program that reads in the grades of 50 students in a course (out of 100 points each ) and then count the number of A students ( grade > 85 ) and the number of B students (grade > 75 ).

Page 22: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• Write a program that reads 100 integer numbers, determines how many positive and negative values have been read, and computes the average of the input values.

Page 23: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• A shop need to keep an inventory of its 100 items for sale. Write a console application to input the item code, price and quantity of each item. Then the program displays a neat table of all items (code, price and quantity) with two asterisks ** next to items whose price > 100 pounds, and one asterisk * next to items whose price is between 50 and 100 pounds.

Page 24: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

24

Example

In one university, it has a rule that at least 75% of

student in each course must pass. This means that

the pass mark for each course will differ. Write a

program that will read 100 students’ marks and

determine the pass mark.

Page 25: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Welcome4.cs

Message Box

// Printing multiple lines in a dialog Box.

using System;

using System.Windows.Forms;

class Welcome4

{

static void Main( string[] args )

{

MessageBox.Show( "Welcome \n to \n C# \n programming!" );} }

25

Page 26: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

26

Simple Program

• Graphical User Interface

– GUIs are used to make it easier to get data from the

user as well as display data to the user

– Message boxes

• Within the System.Windows.Forms

namespace

• Used to prompt or display information to the user

Page 27: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

27

Simple Program

Add Reference dialogue

•Many compiled classes need to be referenced before they can be used in classes

•Assemblies are the packing unit for code in C#

•Namespaces group related classes together

Page 28: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Simple Program

References folder

Solution Explorer

System.Windows.Forms reference

Adding a reference to an assembly in Visual Studio .NET (part 2).

Page 29: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

29

• Message boxes– Buttons

• OK• OKCancel• YesNo• AbortRetryIgnore• YesNoCancel• RetryCancel

- Icons• Exclamation• Question• Error• Information

• Formatting– (variable : format)

Page 30: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

using System;

using System.Windows.Forms;

class Sum {

static void Main( string[] args ) {

int sum = 0;

for ( int number = 2; number <= 100; number += 2 )

sum += number;

MessageBox.Show( "The sum is " + sum, "Sum Even Integers from 2

to 100", MessageBoxButtons.OK, MessageBoxIcon.Information ); }

}

Page 31: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Argument 4: MessageBox Icon (Optional)

Argument 3: OK dialog button. (Optional)

Argument 2: Title bar string (Optional)

Argument 1: Message to display

Page 32: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

32

Examples Using the for Structure

MessageBox Icons Icon Description MessageBoxIcon.Exclamation

Displays a dialog with an exclamation point. Typically used to caution the user against potential problems.

MessageBoxIcon.Information

Displays a dialog with an informational message to the user.

MessageBoxIcon.Question

Displays a dialog with a question mark. Typically used to ask the user a question.

MessageBoxIcon.Error

Displays a dialog with an x in a red circle. Helps alert user of errors or important messages.

Fig. 5.6 Icons for message dialogs.

Page 33: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

33

MessageBox Buttons Description MessageBoxButton.OK Specifies that the dialog should include an OK button.

MessageBoxButton.OKCancel Specifies that the dialog should include OK and Cancel buttons. Warns the user about some condition and allows the user to either continue or cancel an operation.

MessageBoxButton.YesNo Specifies that the dialog should contain Yes and No buttons. Used to ask the user a question.

MessageBoxButton.YesNoCancel Specifies that the dialog should contain Yes, No and Cancel buttons. Typically used to ask the user a question but still allows the user to cancel the operation.

MessageBoxButton.RetryCancel Specifies that the dialog should contain Retry and Cancel buttons. Typically used to inform a user about a failed operation and allow the user to retry or cancel the operation.

MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort, Retry and Ignore buttons. Typically used to inform the user that one of a series of operations has failed and allow the user to abort the series of operations, retry the failed operation or ignore the failed operation and continue.

Fig. 5.7 Buttons for message dialogs.

Page 34: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Write a console application has input a non-negative integer and show a string of binary bits representing n.

Page 35: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

) (1/2 mark per correct circle, -1/2 mark per incorrect circle) Circle the syntax or logic errors in the following C# class and briefly explain what is wrong beside your circle.

class TempConv;

{

public void main( );

{

double BASE_TEMP = 30;

int Deg_C

float Deg_F;

Console.WriteLine( 'Please enter a temperature in degrees C ' );

Deg_C = console.readline();

Deg = (BASE_TEMP + (9 / 5) * (int) Deg_C);

Console.WriteLine('The Fahrenheit temperature is ' + Deg_F + '.');

}

}

35

Page 36: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• Write a code in each button of the flowing windows application that calculates the electricity bill. the price of the electricity rate is 10 for each kilowatt for governmental use, 5 for home use and 20 for commercial use. The command “Clear” removes the old values from the texts in the program

36

Page 37: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• Construct C# console application to solve the following problem. A football team plays n games per year in its league. Given n and the scores of all of the games the team played this year (both the team’s score and its opponent’s score for each game), compute the team’s margin of victory in the games that it played (win = 3, tied = 1 and ignore lost).

37

Page 38: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

Example

• We wish to solve the following problem using C#. given an array A, print all permutations of A (print all values of A in every possible order). For example, A contained the strings “apple”, “banana”, and “coconut”, the desired output is:

• apple banana coconut• apple coconut banana• banana apple coconut• banana coconut apple• coconut apple banana• coconut banana apple

38

Page 39: Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when

• Write a Java application which prints a triangle of x's and y's like the one below. Each new line will have one more x or y than the preceding line. The program should stop after it prints a line with 80 characters in it. You may make use of both the

• Write() and WriteLine() methods. For example;• x• yy• xxx• yyyy• xxxxx

39