Advanced Programming LOOP. 2 Control Structures Program of control –Program performs one statement...
-
Upload
chad-gordon -
Category
Documents
-
view
226 -
download
0
Transcript of Advanced Programming LOOP. 2 Control Structures Program of control –Program performs one statement...
Advanced Programming
LOOPLOOP
2
Control Structures
• Program of control
– Program performs one statement then goes to next line
• Sequential execution– Different statement other than the next one executes
• Selection structure
– The if and if/else statements
– The goto statement
• No longer used unless absolutely needed
• Causes many readability problems• Repetition structure
– The while and do/while loops
– The for and foreach loops
Control Statements
• If, Else
• While
• For
• Foreach
4
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
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.
// 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
{
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
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
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
// 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 +” “);
}
}
11
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
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 );}}
13
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.
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!" );} }
14
15
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
16
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
Simple Program
References folder
Solution Explorer
System.Windows.Forms reference
Adding a reference to an assembly in Visual Studio .NET (part 2).
18
• Message boxes– Buttons
• OK• OKCancel• YesNo• AbortRetryIgnore• YesNoCancel• RetryCancel
- Icons• Exclamation• Question• Error• Information
• Formatting– (variable : format)
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 ); }
}
Argument 4: MessageBox Icon (Optional)
Argument 3: OK dialog button. (Optional)
Argument 2: Title bar string (Optional)
Argument 1: Message to display
21
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.
22
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.
A number of students are answering a questionnaire form that has 25 questions. Answer to each question is given as an integer number ranging from 1 to 5. Write a program that first reads the number of students that have left the fulfilled questionnaire. After that the programs reads answers so that first answers of the first student are entered starting from question 1 and ending to question 25.
Answers of second student are then read in similar way. When all answers are entered the program finds out what are questions (if any) to which all students have given the same answer. Finally the program displays those questions (the question numbers).
Pascal’s triangle looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
The number in each cell of each row is the sum of the numbers in the two cells above it. Write a method Pascal (int rows ) to print Pascal's triangle with number of rows
is row.
Write a console application has input a non-negative integer and show a string of binary bits representing n.
) (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 + '.');
}
}
26
• 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
27
• 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).
28