Download cshtp3_03_IMIntroduction

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
3
What’s in a name?
That which we call a rose
by any other name
would smell as sweet.
—William Shakespeare
When faced with a decision,
I always ask, “What would
be the most fun?”
Introduction
to C#
Applications
OBJECTIVES
In this chapter you’ll learn:
■
—Peggy Walker
■
“Take some more tea,” the
March Hare said to Alice,
very earnestly. “I’ve had
nothing yet,” Alice replied in
an offended tone, “so I can’t
take more.” “You mean you
can’t take less,” said the
Hatter: “it’s very easy to take
more than nothing.”
—Lewis Carroll
To write simple C# applications using code rather than
visual programming.
To write statements that input and output data to the
screen.
■
To declare and use data of various types.
■
To store and retrieve data from memory.
■
To use arithmetic operators.
■
To determine the order in which operators are applied.
■
To write decision-making statements.
■
To use relational and equality operators.
■
To use message dialogs to display messages.
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
2
Chapter 3
Introduction to C# Applications
Self-Review Exercises
3.1
Fill in the blanks in each of the following statements:
a) A(n)
begins the body of every method, and a(n)
body of every method.
ANS: left brace ({), right brace (}).
b) Most statements end with a(n)
.
ANS: semicolon (;).
c) The
statement is used to make decisions.
ANS: if.
d)
ends the
begins a single-line comment.
ANS: //.
e)
,
and
are called whitespace characters. Newline
characters are also considered whitespace characters.
ANS: Blank lines, space characters, tab characters.
f)
are reserved for use by C#.
ANS: Keywords.
.
g) C# applications begin execution at method
ANS: Main.
h) Methods
and
display information in the console window.
ANS: Console.WriteLine and Console.Write.
3.2
State whether each of the following is true or false. If false, explain why.
a) Comments cause the computer to display the text after the // on the screen when the
application executes.
ANS: False. Comments do not cause any action to be performed when the application executes. They are used to document applications and improve their readability.
b) C# considers the variables number and NuMbEr to be identical.
ANS: False. C# is case sensitive, so these variables are distinct.
c) The remainder operator (%) can be used only with integer operands.
ANS: False. The remainder operator can also be used with noninteger operands in C#.
d) The arithmetic operators *, /, %, + and - all have the same level of precedence.
ANS: False. The operators *, / and % are on the same level of precedence, and the operators
+ and - are on a lower level of precedence.
3.3
Write statements to accomplish each of the following tasks:
a) Declare variables c, thisIsAVariable, q76354 and number to be of type int.
ANS: int c, thisIsAVariable, q76354, number;
or
int c;
int thisIsAVariable;
int q76354;
int number;
b) Prompt the user to enter an integer.
ANS: Console.Write( "Enter an integer: " );
c) Input an integer and assign the result to int variable value.
ANS: value = Convert.ToInt32( Console.ReadLine() );
d) If the variable number is not equal to 7, display "The variable number is not equal to 7".
ANS: if ( number != 7 )
Console.WriteLine( "The variable number is not equal to 7" );
e) Display "This
is a C# application"
on one line in the console window.
ANS: Console.WriteLine( "This is a C# application" );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Self-Review Exercises
3
f) Display "This is a C# application" on two lines in the console window. The first line
should end with C#. Use method Console.WriteLine.
ANS: Console.WriteLine( "This is a C#\napplication" );
g) Display "This is a C# application" on two lines in the console window. The first line
should end with C#. Use method Console.WriteLine and two format items.
ANS: Console.WriteLine( "{0}\n{1}", "This is a C#", "application" );
3.4
Identify and correct the errors in each of the following statements:
a) if ( c < 7 );
Console.WriteLine( "c is less than 7" );
ANS: Error: Semicolon after the right parenthesis of the condition ( c < 7 ) in the if state-
b)
ment.
Correction: Remove the semicolon after the right parenthesis. [Note: The error would
cause the output statement to execute regardless of whether the condition in the if
is true.]
if ( c => 7 )
Console.WriteLine( "c is equal to or greater than 7" );
ANS: Error: The relational operator => is incorrect.
Correction: Change => to >=.
3.5
Write declarations, statements or comments that accomplish each of the following tasks:
a) State that an application will calculate the product of three integers.
ANS: // Calculating the product of three integers
b) Declare the variables x, y, z and result to be of type int.
ANS: int x, y, z, result;
or
int x;
int y;
int z;
int result;
c) Prompt the user to enter the first integer.
ANS: Console.Write( "Enter first integer: " );
d) Read the first integer from the user and store it in the variable x.
ANS: x = Convert.ToInt32( Console.ReadLine() );
e) Prompt the user to enter the second integer.
ANS: Console.Write( "Enter second integer: " );
f) Read the second integer from the user and store it in the variable y.
ANS: y = Convert.ToInt32( Console.ReadLine() );
g) Prompt the user to enter the third integer.
ANS: Console.Write( "Enter third integer: " );
h) Read the third integer from the user and store it in the variable z.
ANS: z = Convert.ToInt32( Console.ReadLine() );
i) Compute the product of the three integers contained in variables x, y and z, and assign
the result to the variable result.
ANS: result = x * y * z;
j) Display the message "Product is" followed by the value of the variable result.
ANS: Console.WriteLine( "Product is {0}", result );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
4
Chapter 3
Introduction to C# Applications
3.6
Using the statements you wrote in Exercise 3.5, write a complete application that calculates
and displays the product of three integers.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Exercise 3.6: Product.cs
// Calculating the product of three integers.
using System;
public class Product
{
public static void Main( string[] args )
{
int x; // stores first number to be entered by user
int y; // stores second number to be entered by user
int z; // stores third number to be entered by user
int result; // product of numbers
Console.Write( "Enter first integer: " ); // prompt for input
x = Convert.ToInt32( Console.ReadLine() ); // read first integer
Console.Write( "Enter second integer: " ); // prompt for input
y = Convert.ToInt32( Console.ReadLine() ); // read second integer
Console.Write( "Enter third integer: " ); // prompt for input
z = Convert.ToInt32( Console.ReadLine() ); // read third integer
result = x * y * z; // calculate the product of the numbers
Console.WriteLine( "Product is {0}", result );
} // end Main
} // end class Product
Enter first integer: 10
Enter second integer: 20
Enter third integer: 30
Product is 6000
Exercises
3.7
Fill in the blanks in each of the following statements:
a)
are used to document an application and improve its readability.
ANS: Comments.
b) A decision can be made in a C# application with a(n)
.
ANS: if statement.
c) Calculations are normally performed by
statements.
ANS: assignment.
d) The arithmetic operators with the same precedence as multiplication are
and
.
ANS: division (/), remainder (%)
e) When parentheses in an arithmetic expression are nested, the
set of parentheses is evaluated first.
ANS: innermost.
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
5
f) A location in the computer’s memory that may contain different values at various times
throughout the execution of an application is called a(n)
.
ANS: variable.
3.8
Write C# statements that accomplish each of the following tasks:
a) Display the message "Enter an integer: ", leaving the cursor on the same line.
ANS: Console.Write( "Enter an integer: " );
b) Assign the product of variables b and c to variable a.
ANS: a = b * c;
c) State that an application performs a simple payroll calculation (i.e., use text that helps
to document an application).
ANS: // This application performs a simple payroll calculation.
3.9
State whether each of the following is true or false. If false, explain why.
a) C# operators are evaluated from left to right.
ANS: False. Some operators (e.g., assignment, =) evaluate from right to left.
b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales,
his_account_total, a, b, c, z and z2.
ANS: True.
c) A valid C# arithmetic expression with no parentheses is evaluated from left to right.
ANS: False. The expression is evaluated according to operator precedence and associativity.
d) The following are all invalid variable names: 3g, 87, 67h2, h22 and 2h.
ANS: False. Identifier h22 is a valid variable name.
3.10
Assuming that x = 2 and y = 3, what does each of the following statements display?
a) Console.WriteLine( "x = {0}", x );
ANS: x = 2
b)
Console.WriteLine( "Value of {0} + {0} is {1}", x, ( x + x ) );
ANS: Value of 2 + 2 is 4
c)
Console.Write( "x =" );
ANS: x =
d)
Console.WriteLine( "{0} = {1}", ( x + y ), ( y + x ) );
ANS: 5 = 5
3.11
Which of the following C# statements contain variables whose values are modified?
a) p = i + j + k + 7;
b) Console.WriteLine( "variables whose values are modified" );
c) Console.WriteLine( "a = 5" );
d) value = Convert.ToInt32( Console.ReadLine() );
ANS: (a), (d).
3.12
Given that y = ax3 + 7, which of the following are correct C# statements for this equation?
a) y = a * x * x * x + 7;
b) y = a * x * x * ( x + 7 );
c) y = ( a * x ) * x * ( x + 7 );
d) y = ( a * x ) * x * x + 7;
e) y = a * ( x * x * x ) + 7;
f) y = a * x * ( x * x + 7 );
ANS: (a), (d), (e).
3.13 State the order of evaluation of the operators in each of the following C# statements and
show the value of x after each statement is performed:
a) x = 7 + 3 * 6 / 2 - 1;
ANS: *, /, +, -, =; Value of x is 15.
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
6
Chapter 3
Introduction to C# Applications
b)
x = 2 % 2 + 2 * 2 - 2 / 2;
c)
x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );
ANS: %, *, /, +, -, =; Value of x is 3.
ANS: x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );
6
4
5
Value of x is 324.
3
1
2
3.14 Write an application that displays the numbers 1 to 4 on the same line, with each pair of
adjacent numbers separated by one space. Write the application using the following techniques:
a) Use one Console.WriteLine statement.
b) Use four Console.Write statements.
c) Use one Console.WriteLine statement with four format items.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
wing how to answer one who speaks,
// Exercise 3.14 Solution: Printing.cs
// Displays the numbers 1 through 4 several ways.
using System;
public class Printing
{
public static void Main( string[] args )
{
Console.Write( "Part (a): " );
// one Console.WriteLine statement
Console.WriteLine( "1 2 3 4" );
Console.Write( "Part (b): " );
// four Console.Write statements
Console.Write( "1 " );
Console.Write( "2 " );
Console.Write( "3 " );
Console.Write( "4\n" );
Console.Write( "Part (c): " );
// one Console.WriteLine statement with four format items
Console.WriteLine( "{0} {1} {2} {3}", 1, 2, 3, 4 );
} // end Main
} // end class Printing
Part (a): 1 2 3 4
Part (b): 1 2 3 4
Part (c): 1 2 3 4
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
7
3.15 Write an application that asks the user to enter two integers, obtains them from the user
and displays their sum, product, difference and quotient (division). Use the techniques shown in
Fig. 3.18.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Exercise 3.15 Solution: Calculate.cs
// Displays the sum, product, difference and quotient of two numbers.
using System;
public class Calculate
{
public static void Main( string[] args )
{
int number1; // first number
int number2; // second number
// prompt for input and read first integer
Console.Write( "Enter first integer: " );
number1 = Convert.ToInt32( Console.ReadLine() );
// prompt for input and read second integer
Console.Write( "Enter second integer: " );
number2 = Convert.ToInt32( Console.ReadLine() );
// display results
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
} // end Main
} // end class Calculate
"\nSum is {0}", ( number1 + number2 ) );
"Product is {0}", ( number1 * number2 ) );
"Difference is {0}", ( number1 - number2 ) );
"Quotient is {0}", ( number1 / number2 ) );
Enter first integer: 45
Enter second integer: 5
Sum is 50
Product is 225
Difference is 40
Quotient is 9
3.16 Write an application that asks the user to enter two integers, obtains them from the user
and displays the larger number followed by the words "is larger". If the numbers are equal, display
the message "These numbers are equal". Use the techniques shown in Fig. 3.26.
ANS:
1
2
3
4
5
6
7
// Exercise 3.16 Solution: Larger.cs
// Application that determines the larger of two numbers.
using System;
public class Larger
{
public static void Main( string[] args )
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
8
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Chapter 3
{
Introduction to C# Applications
int number1; // first number to compare
int number2; // second number to compare
// prompt for input and read first number
Console.Write( "Enter first integer: " );
number1 = Convert.ToInt32( Console.ReadLine() );
// prompt for input and read second number
Console.Write( "Enter second integer: " );
number2 = Convert.ToInt32( Console.ReadLine() );
// determine whether number1 is greater than number2
if ( number1 > number2 )
Console.WriteLine( "{0} is larger", number1 );
// determine whether number1 is less than number2
if ( number1 < number2 )
Console.WriteLine( "{0} is larger", number2 );
// determine whether number1 is equal to number2
if ( number1 == number2 )
Console.WriteLine( "These numbers are equal" );
} // end Main
} // end class Larger
Enter first integer: 10
Enter second integer: 12
12 is larger
Enter first integer: 12
Enter second integer: 10
12 is larger
Enter first integer: 11
Enter second integer: 11
These numbers are equal
3.17 Write an application that inputs three integers from the user and displays the sum, average,
product and smallest and largest of the numbers. Use the techniques shown in Fig. 3.18. [Note: The
calculation of the average in this exercise should result in an integer representation of the average.
So, if the sum of the values is 7, the average should be 2, not 2.3333….]
ANS:
1
2
3
4
5
// Exercise 3.17 Solution: Calculate2.cs
// Perform simple calculations on three integers.
using System;
public class Calculate2
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{
public
{
int
int
int
int
int
int
int
int
9
static void Main( string[] args )
number1; // first number
number2; // second number
number3; // third number
largest; // largest value
smallest; // smallest value
sum; // sum of numbers
product; // product of numbers
average; // average of numbers
// prompt for input and read first integer
Console.Write( "Enter first integer: " );
number1 = Convert.ToInt32( Console.ReadLine() );
// prompt for input and read second integer
Console.Write( "Enter second integer: " );
number2 = Convert.ToInt32( Console.ReadLine() );
// prompt for input and read third integer
Console.Write( "Enter third integer: " );
number3 = Convert.ToInt32( Console.ReadLine() );
// determine largest value
largest = number1; // assume number1 is the largest
if ( number2 > largest ) // determine whether number2 is larger
largest = number2;
if ( number3 > largest ) // determine whether number3 is larger
largest = number3;
// determine smallest value
smallest = number1; // assume number1 is the smallest
if ( number2 < smallest ) // determine whether number2 is smallest
smallest = number2;
if ( number3 < smallest ) // determine whether number3 is smallest
smallest = number3;
// perform calculations
sum = number1 + number2 + number3;
product = number1 * number2 * number3;
average = sum / 3;
// display results
Console.WriteLine( "\nFor the numbers {0}, {1} and {2}",
number1, number2, number3 );
Console.WriteLine( "Largest is {0}", largest );
Console.WriteLine( "Smallest is {0}", smallest );
Console.WriteLine( "Sum is {0}", sum );
Console.WriteLine( "Product is {0}", product );
Console.WriteLine( "Average is {0}", average );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
10
61
62
Chapter 3
Introduction to C# Applications
} // end Main
} // end class Calculate2
Enter first integer: 10
Enter second integer: 20
Enter third integer: 30
For the numbers 10, 20 and 30
Largest is 30
Smallest is 10
Sum is 60
Product is 6000
Average is 20
Enter first integer: 200
Enter second integer: 300
Enter third integer: 100
For the numbers 200, 300 and 100
Largest is 300
Smallest is 100
Sum is 600
Product is 6000000
Average is 200
3.18 Write an application that displays a box, an oval, an arrow and a diamond using asterisks
(*), as follows:
*********
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*********
*
*
*
*
*
*
*
***
***
*
*
*
*
*
*
*
*
***
*****
*
*
*
*
*
*
*
*
*
*
*
*
* *
* *
*
*
*
*
*
*
ANS:
1
2
3
4
5
6
7
8
9
10
// Exercise 3.18 Solution: Shapes.cs
// Application draws four shapes to the console window.
using System;
public class Shapes
{
public static void Main( string[] args )
{
Console.WriteLine( "*********
***
Console.WriteLine( "*
*
*
*
*
***
*
* *
" );
" );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
11
12
13
14
15
16
17
18
19
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
} // end Main
} // end class Shapes
*********
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*********
3.19
*
*
*
*
*
*
*
***
***
*
*
*
*
*
*
*
*
***
*****
*
*
*
*
*
*
"*
*
"*
*
"*
*
"*
*
"*
*
"*
*
"*********
*
*
*
*
*
*
* *
* *
*
*
*
*
*
*
*
*
*
*
*
***
*
*
*
*
*
*
*****
*
*
*
*
*
*
*
*
*
*
*
"
* "
*"
* "
*
* "
* *
"
*
"
11
);
);
);
);
);
);
);
*
What does the following code display?
Console.WriteLine( "*\n**\n***\n****\n*****" );
ANS:
*
**
***
****
*****
3.20
What does the following code display?
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
"*" );
"***" );
"*****" );
"****" );
"**" );
ANS:
*
***
*****
****
**
3.21
What does the following code display?
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
12
Chapter 3
Introduction to C# Applications
Console.Write( "*" );
Console.Write( "***" );
Console.Write( "*****" );
Console.Write( "****" );
Console.WriteLine( "**" );
ANS:
***************
3.22
What does the following code display?
Console.Write( "*" );
Console.WriteLine( "***" );
Console.WriteLine( "*****" );
Console.Write( "****" );
Console.WriteLine( "**" );
ANS:
****
*****
******
3.23
What does the following code display?
Console.WriteLine( "{0}\n{1}\n{2}", "*", "***", "*****" );
ANS:
*
***
*****
3.24 Write an application that reads an integer, then determines and displays whether it is odd
or even. [Hint: Use the remainder operator. An even number is a multiple of 2. Any multiple of 2
leaves a remainder of 0 when divided by 2.]
ANS:
1
2
3
4
5
6
7
8
9
// Exercise 3.24 Solution: OddEven.cs
// Application that determines whether a number is odd or even.
using System;
public class OddEven
{
public static void Main( string[] args )
{
int number; // number
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
10
11
12
13
14
15
16
17
18
19
20
21
22
13
Console.Write( "Enter integer: " ); // prompt for input
number = Convert.ToInt32( Console.ReadLine() ); // read number
// determine whether number is even
if ( number % 2 == 0 )
Console.WriteLine( "Number is even" );
// determine whether number is odd
if ( number % 2 != 0 )
Console.WriteLine( "Number is odd" );
} // end Main
} // end class OddEven
Enter integer: 17
Number is odd
Enter integer: 144
Number is even
3.25 Write an application that reads two integers, determines whether the first is a multiple of
the second and displays the result. [Hint: Use the remainder operator.]
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Exercise 3.25 Solution: Multiple.cs
// Application determines whether the first number entered is a multiple
// of the second number entered.
using System;
public class Multiple
{
public static void Main( string[] args )
{
int firstNumber; // stores first number user enters
int secondNumber; // stores second number user enters
// prompt for input and read first number
Console.Write( "Enter first number: " );
firstNumber = Convert.ToInt32( Console.ReadLine() );
// prompt for input and read second number
Console.Write( "Enter second number: " );
secondNumber = Convert.ToInt32( Console.ReadLine() );
// determine whether firstNumber is a multiple of secondNumber
if ( firstNumber % secondNumber == 0 )
Console.WriteLine( "{0} is a multiple of {1}",
firstNumber, secondNumber );
// determine whether firstNumber is not a multiple of secondNumber
if ( firstNumber % secondNumber != 0 )
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
14
28
29
30
31
Chapter 3
Introduction to C# Applications
Console.WriteLine( "{0} is not a multiple of {1}",
firstNumber, secondNumber );
} // end Main
} // end class Multiple
Enter first number: 10
Enter second number: 2
10 is a multiple of 2
Enter first number: 17
Enter second number: 3
17 is not a multiple of 3
3.26 Here’s a peek ahead. In this chapter, you have learned about integers and the type int. C#
can also represent floating-point numbers that contain decimal points, such as 3.14159. Write an
application that inputs from the user the radius of a circle as an integer and displays the circle’s diameter, circumference and area using the floating-point value 3.14159 for π. Use the techniques
shown in Fig. 3.18. [Note: You may also use the predefined constant Math.PI for the value of π. This
constant is more precise than the value 3.14159. Class Math is defined in namespace System]. Use
the following formulas (r is the radius):
diameter = 2r
circumference = 2πr
area = πr2
Do not store the results of each calculation in a variable. Rather, specify each calculation as the
value that will be output in a Console.WriteLine statement. Note that the values produced by the
circumference and area calculations are floating-point numbers. You’ll learn more about floatingpoint numbers in Chapter 4.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Exercise 3.26 Solution: Circle.cs
// Application that calculates area, circumference
// and diameter for a circle.
using System;
public class Circle
{
public static void Main( string[] args )
{
int radius; // radius of circle
Console.Write( "Enter radius: " ); // prompt for input
radius = Convert.ToInt32( Console.ReadLine() ); // read number
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
( 2 * Math.PI *
} // end Main
"Diameter is {0}", ( 2 * radius ) );
"Area is {0}", ( Math.PI * radius * radius ) );
"Circumference is {0}",
radius ) );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
20
15
} // end class Circle
Enter radius: 3
Diameter is 6
Area is 28.2743338823081
Circumference is 18.8495559215388
3.27
Here’s another peek ahead. In this chapter, you have learned about integers and the type
C# can also represent uppercase letters, lowercase letters and a considerable variety of special
symbols. Every character has a corresponding integer representation. The set of characters a computer uses and the corresponding integer representations for those characters is called that computer’s character set. You can indicate a character value in an application simply by enclosing that
character in single quotes, as in 'A'.
You can determine the integer equivalent of a character by preceding that character with
(int), as in
int.
(int) 'A'
The keyword int in parentheses is known as a cast operator, and the entire expression is called a
cast expression. (You’ll learn about cast operators in Chapter 5.) The following statement outputs a
character and its integer equivalent:
Console.WriteLine( "The character {0} has the value {1}\n",
'A', ( ( int ) 'A' ) );
When the preceding statement executes, it displays the character A and the value 65 (from the socalled Unicode® character set) as part of the string.
Using statements similar to the one shown earlier in this exercise, write an application that
displays the integer equivalents of some uppercase letters, lowercase letters, digits and special symbols. Display the integer equivalents of the following: A B C a b c 0 1 2 $ * + / and the blank
character.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Exercise 3.27 Solution: Display.cs
// Application that displays a Unicode character
// and its integer equivalent.
using System;
public class Display
{
public static void Main( string[] args )
{
Console.WriteLine( "The character {0}
'A', ( ( int ) 'A' ) );
Console.WriteLine( "The character {0}
'B', ( ( int ) 'B' ) );
Console.WriteLine( "The character {0}
'C', ( ( int ) 'C' ) );
Console.WriteLine( "The character {0}
'a', ( ( int ) 'a' ) );
Console.WriteLine( "The character {0}
'b', ( ( int ) 'b' ) );
has the value {1}",
has the value {1}",
has the value {1}",
has the value {1}",
has the value {1}",
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
16
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
The
The
The
The
The
The
The
The
The
The
The
The
The
The
Chapter 3
Introduction to C# Applications
Console.WriteLine( "The
'c', ( ( int ) 'c' )
Console.WriteLine( "The
'0', ( ( int ) '0' )
Console.WriteLine( "The
'1', ( ( int ) '1' )
Console.WriteLine( "The
'2', ( ( int ) '2' )
Console.WriteLine( "The
'$', ( ( int ) '$' )
Console.WriteLine( "The
'*', ( ( int ) '*' )
Console.WriteLine( "The
'+', ( ( int ) '+' )
Console.WriteLine( "The
'/', ( ( int ) '/' )
Console.WriteLine( "The
' ', ( ( int ) ' ' )
} // end Main
} // end class Display
character
character
character
character
character
character
character
character
character
character
character
character
character
character
A
B
C
a
b
c
0
1
2
$
*
+
/
has
has
has
has
has
has
has
has
has
has
has
has
has
has
the
the
the
the
the
the
the
the
the
the
the
the
the
the
value
value
value
value
value
value
value
value
value
value
value
value
value
value
character
);
character
);
character
);
character
);
character
);
character
);
character
);
character
);
character
);
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
{0} has the value {1}",
65
66
67
97
98
99
48
49
50
36
42
43
47
32
3.28 Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and displays the digits separated from one another by
three spaces each. For example, if the user types in the number 42339, the application should display
4
2
3
3
9
Assume that the user enters the correct number of digits. What happens when you execute the
application and type a number with more than five digits? What happens when you execute the
application and type a number with fewer than five digits? [Hint: It is possible to do this exercise
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
17
with the techniques you learned in this chapter. You’ll need to use both division and remainder
operations to “pick off ” each digit.]
ANS: The last two sample outputs show the results of entering integers with fewer than five
digits and more than five digits, respectively.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Exercise 3.28 Solution: Five.cs
// Application breaks apart a five-digit number
using System;
public class Five
{
public static void Main( string[] args )
{
int number; // number input by user
int digit1; // first digit
int digit2; // second digit
int digit3; // third digit
int digit4; // fourth digit
int digit5; // fifth digit
Console.Write( "Enter five-digit integer: " ); // prompt
number = Convert.ToInt32( Console.ReadLine() ); // read number
// determine the five digits
digit1 = number / 10000;
digit2 = number % 10000 / 1000;
digit3 = number % 1000 / 100;
digit4 = number % 100 / 10;
digit5 = number % 10;
// output results
Console.WriteLine( "Digits in {0} are {1} {2} {3} {4}
number, digit1, digit2, digit3, digit4, digit5 );
} // end Main
} // end class Five
{5}",
Enter five-digit integer: 12345
Digits in 12345 are 1 2 3 4 5
Enter five-digit integer: 123
Digits in 123 are 0 0 1 2 3
Enter five-digit integer: 7654321
Digits in 7654321 are 765 4 3 2
1
3.29 Using only the programming techniques you learned in this chapter, write an application
that calculates the squares and cubes of the numbers from 0 to 10 and displays the resulting values
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
18
Chapter 3
Introduction to C# Applications
in table format, as shown below. All calculations should be done in terms of a variable x. [Note: This
application does not require any input from the user.]
number
0
1
2
3
4
5
6
7
8
9
10
square
0
1
4
9
16
25
36
49
64
81
100
cube
0
1
8
27
64
125
216
343
512
729
1000
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Exercise 3.29 Solution: Numbers.cs
// Application displays a table of squares and cubes
// of numbers from 0 to 10.
using System;
public class Numbers
{
public static void Main( string[] args )
{
// display a header for the table
Console.WriteLine( "{0}\t{1}\t{2}", "number", "square", "cube" );
// display x, x squared and x cubed
int x = 0;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 1;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 2;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 3;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 4;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 5;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 6;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 7;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 8;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 9;
Console.WriteLine( "{0}\t{1}\t{2}",
x = 10;
Console.WriteLine( "{0}\t{1}\t{2}",
for each value
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
x, ( x * x ), ( x * x * x ) );
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
36
37
19
} // end Main
} // end class Numbers
number
0
1
2
3
4
5
6
7
8
9
10
square
0
1
4
9
16
25
36
49
64
81
100
cube
0
1
8
27
64
125
216
343
512
729
1000
3.30 Write an application that inputs five numbers and determines and displays the number of
negative numbers input, the number of positive numbers input and the number of zeros input.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Exercise 3.30 Solution: Tally.cs
// Application accepts five numbers as input and displays a tally of the
// number of negatives, positives and zeros.
using System;
public class Tally
{
public static void Main( string[] args )
{
int inputNumber; // stores user input
int zeroTally; // count of 0s
int positiveTally; // count of positive values
int negativeTally; // count of negative values
// initialize counters
zeroTally = 0;
positiveTally = 0;
negativeTally = 0;
// prompt for input and read first number
Console.Write( "Enter first integer: " );
inputNumber = Convert.ToInt32( Console.ReadLine() );
// is the number 0?
if ( inputNumber == 0 )
zeroTally = zeroTally + 1;
// is the number negative?
if ( inputNumber < 0 )
negativeTally = negativeTally + 1;
// is the number positive?
if ( inputNumber > 0 )
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
20
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Chapter 3
Introduction to C# Applications
positiveTally = positiveTally + 1;
// prompt for input and read second number
Console.Write( "Enter second integer: " );
inputNumber = Convert.ToInt32( Console.ReadLine() );
// is the number 0?
if ( inputNumber == 0 )
zeroTally = zeroTally + 1;
// is the number negative?
if ( inputNumber < 0 )
negativeTally = negativeTally + 1;
// is the number positive?
if ( inputNumber > 0 )
positiveTally = positiveTally + 1;
// prompt for input and read third number
Console.Write( "Enter third integer: " );
inputNumber = Convert.ToInt32( Console.ReadLine() );
// is the number 0?
if ( inputNumber == 0 )
zeroTally = zeroTally + 1;
// is the number negative?
if ( inputNumber < 0 )
negativeTally = negativeTally + 1;
// is the number positive?
if ( inputNumber > 0 )
positiveTally = positiveTally + 1;
// prompt for input and read fourth number
Console.Write( "Enter fourth integer: " );
inputNumber = Convert.ToInt32( Console.ReadLine() );
// is the number 0?
if ( inputNumber == 0 )
zeroTally = zeroTally + 1;
// is the number negative?
if ( inputNumber < 0 )
negativeTally = negativeTally + 1;
// is the number positive?
if ( inputNumber > 0 )
positiveTally = positiveTally + 1;
// prompt for input and read fifth number
Console.Write( "Enter fifth integer: " );
inputNumber = Convert.ToInt32( Console.ReadLine() );
// is the number 0?
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
89
if ( inputNumber == 0 )
90
zeroTally = zeroTally + 1;
91
92
// is the number negative?
93
if ( inputNumber < 0 )
94
negativeTally = negativeTally + 1;
95
96
// is the number positive?
97
if ( inputNumber > 0 )
98
positiveTally = positiveTally + 1;
99
100
// create a string describing the results
101
Console.WriteLine( "\nThere are {0} zeros", zeroTally );
102
Console.WriteLine( "There are {0} positive numbers",
103
positiveTally );
104
Console.WriteLine( "There are {0} negative numbers",
105
negativeTally );
106
} // end Main
107 } // end class Tally
Enter
Enter
Enter
Enter
Enter
first integer: 0
second integer: -7
third integer: 3
fourth integer: 13
fifth integer: 5
There are 1 zeros
There are 3 positive numbers
There are 1 negative numbers
© 2009 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
21