Download presentation
Presentation is loading. Please wait.
Published byPhebe Austin Modified over 9 years ago
1
Advanced Programming LOOP
2
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
3
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
4
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);
5
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.
6
// 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 {
7
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
8
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
9
Find output prod = 1; do { prod = prod * m ; m = m + 1 ; } while ( m < 6 ) ; console.writeline(“ prod is “+ prod ) ;
10
10 for Repetition Structure for (int counter = 1; counter <= 5; counter++ ) Initial value of control variableIncrement of control variable Control variablenameFinal value of control variable for keyword Loop-continuation condition
11
// 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 + ” “ ); }
12
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 )
13
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 125 2710 31215 41720 52225 5 * count - 3 2 7 12 17 22
14
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 117 213 39 45 51 -4 * count-4 * count + 21 -417 -813 -129 -165 -201 -4 * count -4 -8 -12 -16 -20
15
15 Example Write a program to display all the numbers divisible by 5 in the range 0 to 5000.
16
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
17
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 );}}
18
18 for ( m=1 ; m<=9 ; m=m+2 ) { x = pow ( m, 2 ); console.writeline(m +” “+ x ); } Find the output
19
Write a C program that reads in 30 integer numbers and then print out their sum and average
20
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
21
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 ).
22
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.
23
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.
24
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.
25
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
26
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
27
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
28
Simple Program References folder Solution Explorer System.Windows.Forms reference Adding a reference to an assembly in Visual Studio.NET (part 2).
29
29 Message boxes –Buttons OK OKCancel YesNo AbortRetryIgnore YesNoCancel RetryCancel - Icons Exclamation Question Error Information Formatting –(variable : format)
30
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 ); } }
31
Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display
32
32 Examples Using the for Structure
33
33
34
Write a console application has input a non-negative integer and show a string of binary bits representing n.
35
) (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
36
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
37
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
38
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
39
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.