Solution Manual for Visual C# How to Program, 6th Edition

Take the stress out of textbook problems with Solution Manual for Visual C# How to Program, 6th Edition, a complete guide to solving every question.

Zoe Jordan
Contributor
4.3
47
5 months ago
Preview (16 of 164 Pages)
100%
Purchase to unlock

Loading document content...

Preview Mode

Sign in to access the full document!

Solution Manual for Visual C# How to Program, 6th Edition

Page 1

1 Introduction to Computers, the Internet and Visual C# O b j e c t i v e s In this chapter you’ll: Learn basic computer hardware, software and data concepts. Be introduced to the different types of computer programming languages. Understand the history of the Visual C# programming language and the Windows operating system. Learn what cloud computing with Microsoft Azure is. Understand the basics of object technology. Be introduced to the history of the Internet and the World Wide Web. Understand the parts that Windows, .NET, Visual Studio and C# play in the C# ecosystem. Test-drive a Visual C# drawing app.

Page 2

Page 3

2 Chapter 1 Introduction to Computers, the Internet and Visual C# Self-Review Exercises 1.1 Fill in the blanks in each of the following statements: a) Computers process data under the control of sequences of instructions called . ANS: computer programs. b) A computer consists of various devices referred to as , such as the keyboard, screen, mouse, hard disks, memory, DVD drives and processing units . ANS: hardware. c) Data items processed by computers form a(n) that becomes larger and more complex in structure as we progress from the simplest data items (called “bits”) to richer data items, such as characters, fields, and so on. ANS: data hierarchy. d) Computers can directly understand only their language, which is composed only of 1s and 0s. ANS: machine. e) The three types of computer programming languages discussed in the chapter are ma- chine languages, and . ANS: assembly languages, high-level languages. f) Programs that translate high-level-language programs into machine language are called . ANS: compilers. g) A(n) processor implements several processors on a single “microchip”—a dual-core processor has two CPUs and a quad-core processor has four CPUs. ANS: multicore. h) Windows 10 introduced the for building Windows apps that run on desktop computers, notebook computers, tablets, phones, Xbox and even Microsoft’s new HoloLens augmented reality holographic headset—all using nearly identical code. ANS: Universal Windows Platform (UWP). 1.2 Fill in the blanks in each of the following statements: a) Objects, or more precisely the that objects come from, are essentially reusable software components. ANS: classes. b) You send messages to an object. Each message is implemented as a method that tells a method of the object to perform its task. ANS: call. c) A new class of objects can be created quickly and conveniently by ; the new class absorbs the characteristics of an existing class, possibly customizing them and add- ing unique characteristics of its own. ANS: inheritance. d) To create the best solutions, you should follow a detailed analysis process for determin- ing your project’s (i.e., defining what the system is supposed to do) and de- veloping a design that satisfies them (i.e., deciding how the system should do it). ANS: requirements. e) Visual C# is driven. You’ll write programs that respond to mouse clicks, key- strokes, timer expirations and touches and finger swipes. ANS: event. f) A key goal of Java is to be able to write programs that will run on a great variety of com- puter systems and computer-control devices. This is sometimes called . ANS: write once, run anywhere. 1.3 Fill in the blanks in each of the following statements:

Page 4

Self-Review Exercises 3 a) The executes .NET programs. ANS: Common Language Runtime (CLR) of the .NET Framework. b) The CLR provides various services to code, such as integrating software com- ponents written in different .NET languages, error handling between such components, enhanced security and more. ANS: managed. c) The ability of a program to run without modification across multiple platforms is known as platform . ANS: independence. d) Visual Studio is a(n) in which C# programs are developed. ANS: IDE. e) You can sell your own Windows Phone apps in the . ANS: Windows Store. 1.4 State whether each of the following is true or false . If false , explain why. a) Software objects model both abstract and real-world things. ANS: True. b) The most popular database model is the relational database in which data is stored in simple tables . A table includes records and fields . ANS: True. c) A database is a collection of data that’s organized for easy access and manipulation. ANS: True. d) Secondary storage data takes much longer to access than data in primary memory, but the cost per unit of secondary storage is much higher than that of primary memory. ANS: False: The cost per unit of secondary storage is much lower than that of primary memory. e) High-level languages allow you to write instructions that look almost like everyday Eng- lish and contain commonly used mathematical expressions. ANS: True. f) An object has attributes that it carries along as it’s used in a program. ANS: True. g) The Transmission Control Protocol (TCP) ensures that messages, consisting of sequen- tially numbered pieces called bytes, were properly routed from sender to receiver, ar- rived intact and were assembled in the correct order ANS: False. The pieces are called packets, not bytes. h) The information-carrying capacity of communications lines on the Internet has in- creased tremendously, while hardware costs have increased. ANS: False. Hardware costs have decreased. i) You can build web-based apps with C# and Microsoft’s ASP.NET technology. ANS: True. j) Java has become the key programming language for the Mac OS X desktop operating system and all iOS-based devices, such as iPods, iPhones and iPads. ANS: False. The language is Swift, not Java. k) Microsoft’s ASP.WEB technology is used to create web apps. ANS: False. It’s ASP.NET technology. l) Microsoft’s Windows operating system is the most widely used desktop operating sys- tem worldwide. ANS: True. 1.5 Arrange these byte measurements in order from smallest to largest: terabyte, megabyte, petabyte, gigabyte and kilobyte. ANS: kilobyte, megabyte, gigabyte, terabyte, petabyte.

Page 5

4 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.6 Describe the two-step translation process for preparing your C# code to execute on your particular computer. ANS: C# code is first compiled into MSIL and placed in an executable file. When the app executes, another compiler called the JIT (just-in-time) compiler in the CLR trans- lates the MSIL in the executable file into machine-language code (for a particular platform). Exercises 1.7 Fill in the blanks in each of the following statements: a) The programs that run on a computer are referred to as . ANS: software b) Systems such as smartphones, appliances, game controllers, cable set-top boxes and au- tomobiles that contain small computers are called . ANS: embedded systems c) Just as characters are composed of bits, are composed of characters or bytes. ANS: fields d) Information on secondary storage devices is ; it’s preserved even when the computer’s power is turned off. ANS: persistent e) Translator programs called convert high-level language code into machine- language code . ANS: compilers f) In object-oriented programming languages, we create a program unit called a(n) to house the set of methods that perform its tasks. ANS: class g) Use a building-block approach to creating your programs. Avoid reinventing the wheel—use existing pieces wherever possible. Such software is a key benefit of object-oriented programming. ANS: reuse 1.8 Fill in the blanks in each of the following statements: a) Although many different OOAD processes exist, a single graphical language for com- municating the results of any OOAD process has come into wide use. This language, known as the , is now the most widely used graphical scheme for modeling ob- ject-oriented systems. ANS: UML b) Tim Berners-Lee developed the for sharing information via “hyperlinked” text documents on the web. ANS: HyperText Markup Language (HTML) c) The CLR is a(n) machine. It is software that manages the execution of pro- grams and hides from them the underlying operating system and hardware. ANS: virtual d) Converting a program to run on a different platform from which it was originally in- tended is called . ANS: porting. e) Microsoft’s Windows is a cloud-computing platform that allows you to de- velop, manage and distribute your apps in the cloud. ANS: Azure. (Instructor Note: "Microsoft’s Windows" should be simply "Microsoft" in this exercise.)

Page 6

Exercises 5 f) By using existing controls—which are objects—you can create powerful apps much faster than if you had to write all the code yourself. This is a key benefit of software . ANS: reuse 1.9 State whether each of the following is true or false . If false , explain why. a) The smallest data item in a computer can assume the value 1 or the value 2 . Such a data item is called a bit (short for “binary digit”—a digit that can assume either of two val- ues). ANS: False. Such items have the value 0 or 1. b) The Unicode character set is a popular subset of ASCII that represents uppercase and lowercase letters, digits and some common special characters. ANS: False. ASCII is a subset of Unicode. c) Each of the following is a form of computer output: data displayed on screens, printed on paper, played as audio or video on PCs and media players, used to control other de- vices, such as robots, 3D printers and “intelligent” appliances. ANS: True. d) Reuse helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning. ANS: True. e) One of the W3C’s primary goals is to make the web universally accessible to everyone regardless of disabilities, language or culture. ANS: True. f) C# is available only on Microsoft Windows. ANS: False. There are ports of C# for other platforms, such as Linux. g) The .NET Framework Class Library has millions of valuable prebuilt classes that have been tested and tuned to maximize performance. ANS: False. Thousands, not millions, of prebuilt classes. h) .NET programs can run on any platform. ANS: False. .NET prorgrams run on the Common Language Runtime, which is a virtual machine. i) The Universal Windows Platform (UWP) is designed to provide a common platform (the underlying system on which apps run) and user experience across all of your devices including personal computers, smartphones, tablets and Xbox Live. ANS: True. 1.10 What is a key advantage of interpreters over compilers? What is a key disadvantage? ANS: A key advantage is that interpreters can execute high-level language programs directly (without the need for compilation). A key disadvantage is that interpreted programs exexute more slowly than compiled programs. 1.11 What is the key advantage of using the new async feature in preference to using old-style multithreading? ANS: The new features simplify asynchronous programming, because the compiler hides much of the associated complexity from the developer. 1.12 What are operating systems? ANS: Operating systems are software systems that make using computers more convenient for users, app developers and system administrators. They provide services that allow each app to execute safely, efficiently and concurrently (i.e., in parallel) with other apps.

Page 7

6 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.13 Why is using cloud-computing resources sometimes preferable to purchasing all the hard- ware you need for your own computer? ANS: Cloud computing gives you the flexibility to increase or decrease computing resourc- es to meet your resource needs at any given time, making it more cost effective than purchasing expensive hardware to ensure that you have enough storage and process- ing power at their occasional peak levels. 1.14 Categorize each of the following items as either hardware or software: a) CPU ANS: Hardware. b) Compiler ANS: Software c) Input unit ANS: Hardware. d) A word-processor program ANS: Software e) A C# program ANS: Software 1.15 Translator programs, such as assemblers and compilers, convert programs from one lan- guage (referred to as the source language) to another language (referred to as the target language). Determine which of the following statements are true and which are false : a) An assembler translates source-language programs into machine-language programs. ANS: True. b) High-level languages are generally machine dependent. ANS: False. A high-level language must be compiled into machine-dependent language be- fore it can be executed. This allows high-level languages to be used on all computers with appropriate compilers. c) A machine-language program requires translation before it can be run on a computer. ANS: False. A machine-language program is native to a specific machine. d) The C# compiler translates high-level-language programs into SMIL. ANS: False. It translates C# into MSIL. 1.16 Expand each of the following acronyms: a) W3C ANS: World Wide Web Consortium b) OOP ANS: Object-Oriented Programming c) CLR ANS: Common Language Runtime d) MSIL ANS: Microsoft Intermediate Language e) UML ANS: Unified Modeling Language f) IDE ANS: Integrated Development Environment 1.17 What are the key benefits of the .NET Framework and the CLR? What are the drawbacks? ANS: The key benefits are portability between operating systems and interoperability be- tween languages. As long as a CLR exists for a platform, it can run any .NET pro- gram. Programmers can concentrate on program logic instead of platform-specific details. Thus, the double compilation (code-to-MSIL, and MSIL-to-machine code) allows for platform independence: Programs can be written once and executed on any

Page 8

Exercises 7 platform supporting the CLR—this is known as platform independence. Code writ- ten once could easily be used on another machine without modification, saving time and money. A second benefit of the .NET framework is language interoperability— software components written in different languages can interact (language indepen- dence). A drawback associated with these features is that .NET programs cannot be run until the .NET Framework is developed for a platform. Another is the overhead of the double compilation that is needed before a .NET-language program can be ex- ecuted. 1.18 What are the advantages to using object-oriented techniques? ANS: Programs that use object-oriented programming techniques are easier to understand, correct and modify. The key advantage with using object-oriented programming is that it tends to produce software that is more understandable, because it is better or- ganized and has fewer maintenance requirements than software produced with earlier methodologies. OOP helps the programmer build applications faster by reusing ex- isting software components that model items in the real world. OOP also helps pro- grammers create new software components that can be reused on future software development projects. Building software quickly, correctly, and economically has been an elusive goal in the software industry. The modular, object-oriented design and implementation approach has been found to increase productivity while reduc- ing development time, errors, and cost. 1.19 You are probably wearing on your wrist one of the world’s most common types of objects— a watch. Discuss how each of the following terms and concepts applies to the notion of a watch: object, attributes and behaviors. ANS: The entire watch is an object that is composed of many other objects (the moving parts, the band, the face, etc.) Watch attributes are time, color, band style, technology (digital or analog), and the like. The behaviors of the watch include setting the time and getting the time. A watch can be considered a specific type of clock (as can an alarm clock). 1.20 What is the key accomplishment of the UML? ANS: It replaced the many different graphical modeling languages with a single (unified) language for modeling that can be used by developers regardless of the different OOAD processes they may use. 1.21 What did the chief benefit of the early Internet prove to be? ANS: Communication by e-mail. Today, that communication is also facilitated by appli- cations such as instant messaging and file transfer. 1.22 What is the key capability of the web? ANS: It allows computer users to locate and view multimedia-based documents on almost any subject over the Internet. 1.23 What is the key vision of Microsoft’s .NET initiative? ANS: To embrace the Internet and the web in the development and use of software. 1.24 How does the .NET Framework Class Library facilitate the development of .NET apps? ANS: First, the Framework Class Library is a large library of reusable classes that reduces development time. Programmers can build software quickly by reusing framework’s classes, rather than building new classes “from scratch.” Second, the Framework Class Library is shared by all of the .NET languages, which means that programmers who work in multiple languages have to learn only one class library.

Page 9

8 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.25 Besides the obvious benefits of reuse made possible by OOP, what do many organizations report as another key benefit of OOP? ANS: That OOP tends to produce software that is more understandable, better organized, and easier to maintain, modify and debug. Making-a-Difference Exercises The Making-a-Difference exercises will ask you to work on problems that really matter to individ- uals, communities, countries and the world. 1.26 (Test Drive: Carbon Footprint Calculator) Some scientists believe that carbon emissions, especially from the burning of fossil fuels, contribute significantly to global warming and that this can be combatted if individuals take steps to limit their use of carbon-based fuels. Various organi- zations and individuals are increasingly concerned about their “carbon footprints.” Websites such as TerraPass http://www.terrapass.com/carbon-footprint-calculator-2/ and Carbon Footprint http://www.carbonfootprint.com/calculator.aspx provide carbon-footprint calculators. Test drive these calculators to determine your carbon foot- print. Exercises in later chapters will ask you to program your own carbon-footprint calculator. To prepare for this, research the formulas for calculating carbon footprints. 1.27 (Test Drive: Body-Mass-Index Calculator) By recent estimates, two-thirds of the people in the United States are overweight and about half of those are obese. This causes significant increases in illnesses such as diabetes and heart disease. To determine whether a person is overweight or obese, you can use a measure called the body mass index (BMI). The United States Department of Health and Human Services provides a BMI calculator at http://www.nhlbi.nih.gov/guidelines/ obesity/BMI/bmicalc.htm . Use it to calculate your own BMI. An exercise in Chapter 3 will ask you to program your own BMI calculator. To prepare for this, research the formulas for calculating BMI. 1.28 (Attributes of Hybrid Vehicles) In this chapter you learned the basics of classes. Now you’ll begin “fleshing out” aspects of a class called “Hybrid Vehicle.” Hybrid vehicles are becoming increas- ingly popular, because they often get much better mileage than purely gasoline-powered vehicles. Browse the web and study the features of four or five of today’s popular hybrid cars, then list as many of their hybrid-related attributes as you can. For example, common attributes include city-miles-per- gallon and highway-miles-per-gallon. Also list the attributes of the batteries (type, weight, etc.). ANS: Manufacturer Type of Hybrid—Battery hybrid (Hybrid Electric Vehicles), Plug-in hybrid, Fuel cell etc. Driver feedback system—so the driver can monitor fuel efficiency based on their driving Energy recovery—for example, regenerative breaking Carbon footprint—tons of CO 2 per year Fuel capacity City-miles-per-gallon Highway-miles-per-gallon Two-mode hybrid propulsion system Engine size—V6, V8, etc. Vehicle type—SUV, crossover, compact, mid-size, etc.

Page 10

Making-a-Difference Exercises 9 Seating capacity Horse power Drive train (front wheel drive, all wheel drive) Top speed Torque Price 1.29 (Gender Neutrality) Some people want to eliminate sexism in all forms of communication. You’ve been asked to create a program that can process a paragraph of text and replace gender-spe- cific words with gender-neutral ones. Assuming that you’ve been given a list of gender-specific words and their gender-neutral replacements (e.g., replace “wife” with “spouse,” “man” with per- son,” “daughter” with “child” and so on), explain the procedure you’d use to read through a para- graph of text and manually perform these replacements. How might your procedure generate a strange term like “woperchild,” which is actually listed in the Urban Dictionary ( www.urbandic- tionary.com )? In Chapter 5, you’ll learn that a more formal term for “procedure” is “algorithm,” and that an algorithm specifies the steps to be performed and the order in which to perform them. ANS: Search through the entire paragraph for a word such as “wife” and replace every oc- currence with “spouse.” Repeat this searching process for every gender specific word in the list. You could accidentally get a word like “woperchild” if you are not careful about how you perform replacements. For example, the word “man” can be part of a larger word, like “woman.” So, replacing every occurrence of “man” can yield strange results. Consider the process of replacing “man” with “person” then replacing “son” with “child.” If you encounter the word “woman,” which contains the word “man,” you’d replace “man” with “person” resulting in the word “woperson.” In a subsequent pass you’d encounter “woperson” and replace “son” with “child” result- ing in the “woperchild.”

Page 11

2 Introduction to Visual Studio and Visual Programming O b j e c t i v e s In this chapter you’ll: Learn the basics of the Visual Studio Community 2015 Integrated Development Environment (IDE) for writing, running and debugging your apps. Create a new project using Visual Studio’s Windows Forms Application template. Be introduced to Windows Form s and the controls you’ll use to build graphical user interfaces. Use key commands contained in the IDE’s menus and toolbars. Understand the purpose of the various windows in the Visual Studio. Use Visual Studio’s help features. Use visual app development to conveniently create, compile and execute a simple Visual C# app that displays text and an image.

Page 12

2 Chapter 2 Introduction to Visual Studio and Visual Programming Self-Review Exercises 2.1 Fill in the blanks in each of the following statements: a) The technique of allows you to create GUIs without writing any code. ANS: visual app development. b) A(n) is a group of one or more projects that collectively form a Visual C# app. ANS: solution. c) The feature hides a window in the IDE. ANS: auto-hide. d) A(n) appears when the mouse pointer hovers over an icon. ANS: tool tip. e) The window allows you to browse solution files. ANS: Solution Explorer . f) The properties in the Properties window can be sorted or . ANS: alphabetically, categorically. g) A Form ’s property specifies the text displayed in the Form ’s title bar. ANS: Text . h) The contains the controls that you can add to a Form . ANS: Toolbox . i) displays relevant help articles, based on the current context. ANS: context-sensitive help. j) The property specifies how text is aligned within a Label ’s boundaries. ANS: TextAlign . 2.2 State whether each of the following is true or false . If false , explain why. a) toggles auto-hide for a window. ANS: False. The pin icon ( ) toggles auto-hide. closes a window. b) The toolbar icons represent various menu commands. ANS: True. c) The toolbar contains icons that represent controls you can drag onto a Form . ANS: False. The Toolbox contains icons that represent such controls. d) Both Form s and Label s have a title bar. ANS: False. Form s have a title bar but Label s do not (although they do have Label text). e) Control properties can be modified only by writing code. ANS: False. Control properties can be modified using the Properties window. f) PictureBox es typically display images. ANS: True. g) Visual C# files use the file extension .csharp . ANS: False. Visual C# files use the file extension .cs . h) A Form ’s background color is set using the BackColor property. ANS: True. Exercises Note: Solutions to the code exercises are located in the sol_ch02 folder 2.3 Fill in the blanks in each of the following statements: a) When an ellipsis button is clicked, a(n) is displayed. ANS: dialog. b) Using help immediately displays a relevant help article. ANS: context-sensitive help.

Page 13

Exercises 3 c) GUI is an acronym for . ANS: graphical user interface. d) The property specifies which image a PictureBox displays. ANS: Image . e) The menu contains commands for arranging and displaying windows. ANS: Window . 2.4 State whether each of the following is true or false . If false , explain why. a) You can add a control to a Form by double clicking its control icon in the Toolbox . ANS: True. b) The Form , Label and PictureBox have identical properties. ANS: False. Each type of control has a different set of properties, although controls can have common properties. c) If your machine is connected to the Internet, you can browse websites from the Visual Studio IDE. ANS: True. d) Visual C# app developers usually create complex apps without writing any code. ANS: False. C# programming usually involves a combination of writing a portion of the program code and having Visual Studio generate the remaining code. e) Sizing handles are visible during execution. ANS: False. Sizing handles are present only in Design view when a Form or control is select- ed. 2.5 Some features that appear throughout Visual Studio perform similar actions in different contexts. Explain and give examples of how the ellipsis buttons, down-arrow buttons and tool tips act in this manner. Why do you think the Visual Studio IDE was designed this way? ANS : An ellipsis button indicates that a dialog will be displayed when the button is clicked. The down-arrow button indicates that there are more options, both for toolbar icons and for items in the Properties window. Moving the mouse pointer over most icons displays the icon’s name as a tool tip. These features make the Visual Studio IDE easier to learn and use. 2.6 Briefly describe each of the following terms: a) toolbar ANS: A toolbar contains icons that, when clicked, execute a command. b) menu bar ANS: A menu bar contains menus, which are groups of related commands. c) Toolbox ANS: The Toolbox contains controls used to customize forms. d) control ANS: A control is a component, such as a PictureBox or Label . Controls are added to a Form . e) Form ANS: A Form represents the Windows Forms application that you are creating. The Form and controls collectively represent the program’s GUI. f) solution ANS: A solution is a group of projects.

Page 14

3 Introduction to C# App Programming O b j e c t i v e s In this chapter you’ll: Write simple C# apps using code rather than visual programming. Input data from the keyboard and output data to the screen. Use C# 6’s string interpolation to create formatted string s by inserting values into string literals. Declare and use data of various types. Store data in memory and retrieve it. Use arithmetic operators. Determine the order in which operators are applied. Write decision-making statements with equality and relational operators.

Page 15

2 Chapter 3 Introduction to C# App Programming 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) ends the 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) begins a single-line comment. ANS: // . e) , and are called whitespace. Newline characters are also considered whitespace. ANS: Blank lines, space characters, tab characters. f) are reserved for use by C#. ANS: Keywords. g) C# apps begin execution at method . ANS: Main . h) Methods and display information in the console window. ANS: Console.WriteLine and Console.Write . i) enables you to insert values directly into a string literal. ANS: string interpolation. 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 app executes. ANS: False. Comments do not cause any action to be performed when the app executes. They’re used to document apps 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 also can 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. e) An interpolated string must begin with a $ before the string literal. ANS: True. 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; 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 = int.Parse(Console.ReadLine());

Page 16

Self-Review Exercises 3 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# app" on one line in the console window. ANS: Console.WriteLine("This is a C# app"); f) Display "This is a C# app" 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#\napp"); g) Write a statement that uses string interpolation to display the sum of the variables x and y . Assume variables x and y of type int exist and already have values. ANS: Console.WriteLine($"The sum of {x} and {y} is {x + y}"); 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- ment. Correction: Remove the semicolon after the right parenthesis. [ Note : With the semi- colon, the output statement executes regardless of whether the condition in the if is true.] b) 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 app 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; 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 = int.Parse(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 = int.Parse(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 = int.Parse(Console.ReadLine());
1 Introduction to Computers, the Internet and Visual C# O b j e c t i v e s In this chapter you’ll: ■ Learn basic computer hardware, software and data concepts. ■ Be introduced to the different types of computer programming languages. ■ Understand the history of the Visual C# programming language and the Windows operating system. ■ Learn what cloud computing with Microsoft Azure is. ■ Understand the basics of object technology. ■ Be introduced to the history of the Internet and the World Wide Web. ■ Understand the parts that Windows, .NET, Visual Studio and C# play in the C# ecosystem. ■ Test-drive a Visual C# drawing app. 2 Chapter 1 Introduction to Computers, the Internet and Visual C# Self-Review Exercises 1.1 Fill in the blanks in each of the following statements: a) Computers process data under the control of sequences of instructions called . ANS: computer programs. b) A computer consists of various devices referred to as , such as the keyboard, screen, mouse, hard disks, memory, DVD drives and processing units . ANS: hardware. c) Data items processed by computers form a(n) that becomes larger and more complex in structure as we progress from the simplest data items (called “bits”) to richer data items, such as characters, fields, and so on. ANS: data hierarchy. d) Computers can directly understand only their language, which is composed only of 1s and 0s. ANS: machine. e) The three types of computer programming languages discussed in the chapter are ma- chine languages, and . ANS: assembly languages, high-level languages. f) Programs that translate high-level-language programs into machine language are called . ANS: compilers. g) A(n) processor implements several processors on a single “microchip”—a dual-core processor has two CPUs and a quad-core processor has four CPUs. ANS: multicore. h) Windows 10 introduced the for building Windows apps that run on desktop computers, notebook computers, tablets, phones, Xbox and even Microsoft’s new HoloLens augmented reality holographic headset—all using nearly identical code. ANS: Universal Windows Platform (UWP). 1.2 Fill in the blanks in each of the following statements: a) Objects, or more precisely the that objects come from, are essentially reusable software components. ANS: classes. b) You send messages to an object. Each message is implemented as a method that tells a method of the object to perform its task. ANS: call. c) A new class of objects can be created quickly and conveniently by ; the new class absorbs the characteristics of an existing class, possibly customizing them and add- ing unique characteristics of its own. ANS: inheritance. d) To create the best solutions, you should follow a detailed analysis process for determin- ing your project’s (i.e., defining what the system is supposed to do) and de- veloping a design that satisfies them (i.e., deciding how the system should do it). ANS: requirements. e) Visual C# is driven. You’ll write programs that respond to mouse clicks, key- strokes, timer expirations and touches and finger swipes. ANS: event. f) A key goal of Java is to be able to write programs that will run on a great variety of com- puter systems and computer-control devices. This is sometimes called . ANS: write once, run anywhere. 1.3 Fill in the blanks in each of the following statements: Self-Review Exercises 3 a) The executes .NET programs. ANS: Common Language Runtime (CLR) of the .NET Framework. b) The CLR provides various services to code, such as integrating software com- ponents written in different .NET languages, error handling between such components, enhanced security and more. ANS: managed. c) The ability of a program to run without modification across multiple platforms is known as platform . ANS: independence. d) Visual Studio is a(n) in which C# programs are developed. ANS: IDE. e) You can sell your own Windows Phone apps in the . ANS: Windows Store. 1.4 State whether each of the following is true or false . If false , explain why. a) Software objects model both abstract and real-world things. ANS: True. b) The most popular database model is the relational database in which data is stored in simple tables . A table includes records and fields . ANS: True. c) A database is a collection of data that’s organized for easy access and manipulation. ANS: True. d) Secondary storage data takes much longer to access than data in primary memory, but the cost per unit of secondary storage is much higher than that of primary memory. ANS: False: The cost per unit of secondary storage is much lower than that of primary memory. e) High-level languages allow you to write instructions that look almost like everyday Eng- lish and contain commonly used mathematical expressions. ANS: True. f) An object has attributes that it carries along as it’s used in a program. ANS: True. g) The Transmission Control Protocol (TCP) ensures that messages, consisting of sequen- tially numbered pieces called bytes, were properly routed from sender to receiver, ar- rived intact and were assembled in the correct order ANS: False. The pieces are called packets, not bytes. h) The information-carrying capacity of communications lines on the Internet has in- creased tremendously, while hardware costs have increased. ANS: False. Hardware costs have decreased. i) You can build web-based apps with C# and Microsoft’s ASP.NET technology. ANS: True. j) Java has become the key programming language for the Mac OS X desktop operating system and all iOS-based devices, such as iPods, iPhones and iPads. ANS: False. The language is Swift, not Java. k) Microsoft’s ASP.WEB technology is used to create web apps. ANS: False. It’s ASP.NET technology. l) Microsoft’s Windows operating system is the most widely used desktop operating sys- tem worldwide. ANS: True. 1.5 Arrange these byte measurements in order from smallest to largest: terabyte, megabyte, petabyte, gigabyte and kilobyte. ANS: kilobyte, megabyte, gigabyte, terabyte, petabyte. 4 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.6 Describe the two-step translation process for preparing your C# code to execute on your particular computer. ANS: C# code is first compiled into MSIL and placed in an executable file. When the app executes, another compiler called the JIT (just-in-time) compiler in the CLR trans- lates the MSIL in the executable file into machine-language code (for a particular platform). Exercises 1.7 Fill in the blanks in each of the following statements: a) The programs that run on a computer are referred to as . ANS: software b) Systems such as smartphones, appliances, game controllers, cable set-top boxes and au- tomobiles that contain small computers are called . ANS: embedded systems c) Just as characters are composed of bits, are composed of characters or bytes. ANS: fields d) Information on secondary storage devices is ; it’s preserved even when the computer’s power is turned off. ANS: persistent e) Translator programs called convert high-level language code into machine- language code . ANS: compilers f) In object-oriented programming languages, we create a program unit called a(n) to house the set of methods that perform its tasks. ANS: class g) Use a building-block approach to creating your programs. Avoid reinventing the wheel—use existing pieces wherever possible. Such software is a key benefit of object-oriented programming. ANS: reuse 1.8 Fill in the blanks in each of the following statements: a) Although many different OOAD processes exist, a single graphical language for com- municating the results of any OOAD process has come into wide use. This language, known as the , is now the most widely used graphical scheme for modeling ob- ject-oriented systems. ANS: UML b) Tim Berners-Lee developed the for sharing information via “hyperlinked” text documents on the web. ANS: HyperText Markup Language (HTML) c) The CLR is a(n) machine. It is software that manages the execution of pro- grams and hides from them the underlying operating system and hardware. ANS: virtual d) Converting a program to run on a different platform from which it was originally in- tended is called . ANS: porting. e) Microsoft’s Windows is a cloud-computing platform that allows you to de- velop, manage and distribute your apps in the cloud. ANS: Azure. (Instructor Note: "Microsoft’s Windows" should be simply "Microsoft" in this exercise.) Exercises 5 f) By using existing controls—which are objects—you can create powerful apps much faster than if you had to write all the code yourself. This is a key benefit of software . ANS: reuse 1.9 State whether each of the following is true or false . If false , explain why. a) The smallest data item in a computer can assume the value 1 or the value 2 . Such a data item is called a bit (short for “binary digit”—a digit that can assume either of two val- ues). ANS: False. Such items have the value 0 or 1. b) The Unicode character set is a popular subset of ASCII that represents uppercase and lowercase letters, digits and some common special characters. ANS: False. ASCII is a subset of Unicode. c) Each of the following is a form of computer output: data displayed on screens, printed on paper, played as audio or video on PCs and media players, used to control other de- vices, such as robots, 3D printers and “intelligent” appliances. ANS: True. d) Reuse helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning. ANS: True. e) One of the W3C’s primary goals is to make the web universally accessible to everyone regardless of disabilities, language or culture. ANS: True. f) C# is available only on Microsoft Windows. ANS: False. There are ports of C# for other platforms, such as Linux. g) The .NET Framework Class Library has millions of valuable prebuilt classes that have been tested and tuned to maximize performance. ANS: False. Thousands, not millions, of prebuilt classes. h) .NET programs can run on any platform. ANS: False. .NET prorgrams run on the Common Language Runtime, which is a virtual machine. i) The Universal Windows Platform (UWP) is designed to provide a common platform (the underlying system on which apps run) and user experience across all of your devices including personal computers, smartphones, tablets and Xbox Live. ANS: True. 1.10 What is a key advantage of interpreters over compilers? What is a key disadvantage? ANS: A key advantage is that interpreters can execute high-level language programs directly (without the need for compilation). A key disadvantage is that interpreted programs exexute more slowly than compiled programs. 1.11 What is the key advantage of using the new async feature in preference to using old-style multithreading? ANS: The new features simplify asynchronous programming, because the compiler hides much of the associated complexity from the developer. 1.12 What are operating systems? ANS: Operating systems are software systems that make using computers more convenient for users, app developers and system administrators. They provide services that allow each app to execute safely, efficiently and concurrently (i.e., in parallel) with other apps. 6 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.13 Why is using cloud-computing resources sometimes preferable to purchasing all the hard- ware you need for your own computer? ANS: Cloud computing gives you the flexibility to increase or decrease computing resourc- es to meet your resource needs at any given time, making it more cost effective than purchasing expensive hardware to ensure that you have enough storage and process- ing power at their occasional peak levels. 1.14 Categorize each of the following items as either hardware or software: a) CPU ANS: Hardware. b) Compiler ANS: Software c) Input unit ANS: Hardware. d) A word-processor program ANS: Software e) A C# program ANS: Software 1.15 Translator programs, such as assemblers and compilers, convert programs from one lan- guage (referred to as the source language) to another language (referred to as the target language). Determine which of the following statements are true and which are false : a) An assembler translates source-language programs into machine-language programs. ANS: True. b) High-level languages are generally machine dependent. ANS: False. A high-level language must be compiled into machine-dependent language be- fore it can be executed. This allows high-level languages to be used on all computers with appropriate compilers. c) A machine-language program requires translation before it can be run on a computer. ANS: False. A machine-language program is native to a specific machine. d) The C# compiler translates high-level-language programs into SMIL. ANS: False. It translates C# into MSIL. 1.16 Expand each of the following acronyms: a) W3C ANS: World Wide Web Consortium b) OOP ANS: Object-Oriented Programming c) CLR ANS: Common Language Runtime d) MSIL ANS: Microsoft Intermediate Language e) UML ANS: Unified Modeling Language f) IDE ANS: Integrated Development Environment 1.17 What are the key benefits of the .NET Framework and the CLR? What are the drawbacks? ANS: The key benefits are portability between operating systems and interoperability be- tween languages. As long as a CLR exists for a platform, it can run any .NET pro- gram. Programmers can concentrate on program logic instead of platform-specific details. Thus, the double compilation (code-to-MSIL, and MSIL-to-machine code) allows for platform independence: Programs can be written once and executed on any Exercises 7 platform supporting the CLR—this is known as platform independence. Code writ- ten once could easily be used on another machine without modification, saving time and money. A second benefit of the .NET framework is language interoperability— software components written in different languages can interact (language indepen- dence). A drawback associated with these features is that .NET programs cannot be run until the .NET Framework is developed for a platform. Another is the overhead of the double compilation that is needed before a .NET-language program can be ex- ecuted. 1.18 What are the advantages to using object-oriented techniques? ANS: Programs that use object-oriented programming techniques are easier to understand, correct and modify. The key advantage with using object-oriented programming is that it tends to produce software that is more understandable, because it is better or- ganized and has fewer maintenance requirements than software produced with earlier methodologies. OOP helps the programmer build applications faster by reusing ex- isting software components that model items in the real world. OOP also helps pro- grammers create new software components that can be reused on future software development projects. Building software quickly, correctly, and economically has been an elusive goal in the software industry. The modular, object-oriented design and implementation approach has been found to increase productivity while reduc- ing development time, errors, and cost. 1.19 You are probably wearing on your wrist one of the world’s most common types of objects— a watch. Discuss how each of the following terms and concepts applies to the notion of a watch: object, attributes and behaviors. ANS: The entire watch is an object that is composed of many other objects (the moving parts, the band, the face, etc.) Watch attributes are time, color, band style, technology (digital or analog), and the like. The behaviors of the watch include setting the time and getting the time. A watch can be considered a specific type of clock (as can an alarm clock). 1.20 What is the key accomplishment of the UML? ANS: It replaced the many different graphical modeling languages with a single (unified) language for modeling that can be used by developers regardless of the different OOAD processes they may use. 1.21 What did the chief benefit of the early Internet prove to be? ANS: Communication by e-mail. Today, that communication is also facilitated by appli- cations such as instant messaging and file transfer. 1.22 What is the key capability of the web? ANS: It allows computer users to locate and view multimedia-based documents on almost any subject over the Internet. 1.23 What is the key vision of Microsoft’s .NET initiative? ANS: To embrace the Internet and the web in the development and use of software. 1.24 How does the .NET Framework Class Library facilitate the development of .NET apps? ANS: First, the Framework Class Library is a large library of reusable classes that reduces development time. Programmers can build software quickly by reusing framework’s classes, rather than building new classes “from scratch.” Second, the Framework Class Library is shared by all of the .NET languages, which means that programmers who work in multiple languages have to learn only one class library. 8 Chapter 1 Introduction to Computers, the Internet and Visual C# 1.25 Besides the obvious benefits of reuse made possible by OOP, what do many organizations report as another key benefit of OOP? ANS: That OOP tends to produce software that is more understandable, better organized, and easier to maintain, modify and debug. Making-a-Difference Exercises The Making-a-Difference exercises will ask you to work on problems that really matter to individ- uals, communities, countries and the world. 1.26 (Test Drive: Carbon Footprint Calculator) Some scientists believe that carbon emissions, especially from the burning of fossil fuels, contribute significantly to global warming and that this can be combatted if individuals take steps to limit their use of carbon-based fuels. Various organi- zations and individuals are increasingly concerned about their “carbon footprints.” Websites such as TerraPass http://www.terrapass.com/carbon-footprint-calculator-2/ and Carbon Footprint http://www.carbonfootprint.com/calculator.aspx provide carbon-footprint calculators. Test drive these calculators to determine your carbon foot- print. Exercises in later chapters will ask you to program your own carbon-footprint calculator. To prepare for this, research the formulas for calculating carbon footprints. 1.27 (Test Drive: Body-Mass-Index Calculator) By recent estimates, two-thirds of the people in the United States are overweight and about half of those are obese. This causes significant increases in illnesses such as diabetes and heart disease. To determine whether a person is overweight or obese, you can use a measure called the body mass index (BMI). The United States Department of Health and Human Services provides a BMI calculator at http://www.nhlbi.nih.gov/guidelines/ obesity/BMI/bmicalc.htm . Use it to calculate your own BMI. An exercise in Chapter 3 will ask you to program your own BMI calculator. To prepare for this, research the formulas for calculating BMI. 1.28 (Attributes of Hybrid Vehicles) In this chapter you learned the basics of classes. Now you’ll begin “fleshing out” aspects of a class called “Hybrid Vehicle.” Hybrid vehicles are becoming increas- ingly popular, because they often get much better mileage than purely gasoline-powered vehicles. Browse the web and study the features of four or five of today’s popular hybrid cars, then list as many of their hybrid-related attributes as you can. For example, common attributes include city-miles-per- gallon and highway-miles-per-gallon. Also list the attributes of the batteries (type, weight, etc.). ANS: • Manufacturer • Type of Hybrid—Battery hybrid (Hybrid Electric Vehicles), Plug-in hybrid, Fuel cell etc. • Driver feedback system—so the driver can monitor fuel efficiency based on their driving • Energy recovery—for example, regenerative breaking • Carbon footprint—tons of CO 2 per year • Fuel capacity • City-miles-per-gallon • Highway-miles-per-gallon • Two-mode hybrid propulsion system • Engine size—V6, V8, etc. • Vehicle type—SUV, crossover, compact, mid-size, etc. Making-a-Difference Exercises 9 • Seating capacity • Horse power • Drive train (front wheel drive, all wheel drive) • Top speed • Torque • Price 1.29 (Gender Neutrality) Some people want to eliminate sexism in all forms of communication. You’ve been asked to create a program that can process a paragraph of text and replace gender-spe- cific words with gender-neutral ones. Assuming that you’ve been given a list of gender-specific words and their gender-neutral replacements (e.g., replace “wife” with “spouse,” “man” with “ per- son,” “daughter” with “child” and so on), explain the procedure you’d use to read through a para- graph of text and manually perform these replacements. How might your procedure generate a strange term like “woperchild,” which is actually listed in the Urban Dictionary ( www.urbandic- tionary.com )? In Chapter 5, you’ll learn that a more formal term for “procedure” is “algorithm,” and that an algorithm specifies the steps to be performed and the order in which to perform them. ANS: Search through the entire paragraph for a word such as “wife” and replace every oc- currence with “spouse.” Repeat this searching process for every gender specific word in the list. You could accidentally get a word like “woperchild” if you are not careful about how you perform replacements. For example, the word “man” can be part of a larger word, like “woman.” So, replacing every occurrence of “man” can yield strange results. Consider the process of replacing “man” with “person” then replacing “son” with “child.” If you encounter the word “woman,” which contains the word “man,” you’d replace “man” with “person” resulting in the word “woperson.” In a subsequent pass you’d encounter “woperson” and replace “son” with “child” result- ing in the “woperchild.” 2 Introduction to Visual Studio and Visual Programming O b j e c t i v e s In this chapter you’ll: ■ Learn the basics of the Visual Studio Community 2015 Integrated Development Environment (IDE) for writing, running and debugging your apps. ■ Create a new project using Visual Studio’s Windows Forms Application template. ■ Be introduced to Windows Form s and the controls you’ll use to build graphical user interfaces. ■ Use key commands contained in the IDE’s menus and toolbars. ■ Understand the purpose of the various windows in the Visual Studio. ■ Use Visual Studio’s help features. ■ Use visual app development to conveniently create, compile and execute a simple Visual C# app that displays text and an image. 2 Chapter 2 Introduction to Visual Studio and Visual Programming Self-Review Exercises 2.1 Fill in the blanks in each of the following statements: a) The technique of allows you to create GUIs without writing any code. ANS: visual app development. b) A(n) is a group of one or more projects that collectively form a Visual C# app. ANS: solution. c) The feature hides a window in the IDE. ANS: auto-hide. d) A(n) appears when the mouse pointer hovers over an icon. ANS: tool tip. e) The window allows you to browse solution files. ANS: Solution Explorer . f) The properties in the Properties window can be sorted or . ANS: alphabetically, categorically. g) A Form ’s property specifies the text displayed in the Form ’s title bar. ANS: Text . h) The contains the controls that you can add to a Form . ANS: Toolbox . i) displays relevant help articles, based on the current context. ANS: context-sensitive help. j) The property specifies how text is aligned within a Label ’s boundaries. ANS: TextAlign . 2.2 State whether each of the following is true or false . If false , explain why. a) toggles auto-hide for a window. ANS: False. The pin icon ( ) toggles auto-hide. closes a window. b) The toolbar icons represent various menu commands. ANS: True. c) The toolbar contains icons that represent controls you can drag onto a Form . ANS: False. The Toolbox contains icons that represent such controls. d) Both Form s and Label s have a title bar. ANS: False. Form s have a title bar but Label s do not (although they do have Label text). e) Control properties can be modified only by writing code. ANS: False. Control properties can be modified using the Properties window. f) PictureBox es typically display images. ANS: True. g) Visual C# files use the file extension .csharp . ANS: False. Visual C# files use the file extension .cs . h) A Form ’s background color is set using the BackColor property. ANS: True. Exercises Note: Solutions to the code exercises are located in the sol_ch02 folder 2.3 Fill in the blanks in each of the following statements: a) When an ellipsis button is clicked, a(n) is displayed. ANS: dialog. b) Using help immediately displays a relevant help article. ANS: context-sensitive help. Exercises 3 c) GUI is an acronym for . ANS: graphical user interface. d) The property specifies which image a PictureBox displays. ANS: Image . e) The menu contains commands for arranging and displaying windows. ANS: Window . 2.4 State whether each of the following is true or false . If false , explain why. a) You can add a control to a Form by double clicking its control icon in the Toolbox . ANS: True. b) The Form , Label and PictureBox have identical properties. ANS: False. Each type of control has a different set of properties, although controls can have common properties. c) If your machine is connected to the Internet, you can browse websites from the Visual Studio IDE. ANS: True. d) Visual C# app developers usually create complex apps without writing any code. ANS: False. C# programming usually involves a combination of writing a portion of the program code and having Visual Studio generate the remaining code. e) Sizing handles are visible during execution. ANS: False. Sizing handles are present only in Design view when a Form or control is select- ed. 2.5 Some features that appear throughout Visual Studio perform similar actions in different contexts. Explain and give examples of how the ellipsis buttons, down-arrow buttons and tool tips act in this manner. Why do you think the Visual Studio IDE was designed this way? ANS : An ellipsis button indicates that a dialog will be displayed when the button is clicked. The down-arrow button indicates that there are more options, both for toolbar icons and for items in the Properties window. Moving the mouse pointer over most icons displays the icon’s name as a tool tip. These features make the Visual Studio IDE easier to learn and use. 2.6 Briefly describe each of the following terms: a) toolbar ANS: A toolbar contains icons that, when clicked, execute a command. b) menu bar ANS: A menu bar contains menus, which are groups of related commands. c) Toolbox ANS: The Toolbox contains controls used to customize forms. d) control ANS: A control is a component, such as a PictureBox or Label . Controls are added to a Form . e) Form ANS: A Form represents the Windows Forms application that you are creating. The Form and controls collectively represent the program’s GUI. f) solution ANS: A solution is a group of projects. 3 Introduction to C# App Programming O b j e c t i v e s In this chapter you’ll: ■ Write simple C# apps using code rather than visual programming. ■ Input data from the keyboard and output data to the screen. ■ Use C# 6’s string interpolation to create formatted string s by inserting values into string literals. ■ Declare and use data of various types. ■ Store data in memory and retrieve it. ■ Use arithmetic operators. ■ Determine the order in which operators are applied. ■ Write decision-making statements with equality and relational operators. 2 Chapter 3 Introduction to C# App Programming 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) ends the 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) begins a single-line comment. ANS: // . e) , and are called whitespace. Newline characters are also considered whitespace. ANS: Blank lines, space characters, tab characters. f) are reserved for use by C#. ANS: Keywords. g) C# apps begin execution at method . ANS: Main . h) Methods and display information in the console window. ANS: Console.WriteLine and Console.Write . i) enables you to insert values directly into a string literal. ANS: string interpolation. 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 app executes. ANS: False. Comments do not cause any action to be performed when the app executes. They’re used to document apps 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 also can 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. e) An interpolated string must begin with a $ before the string literal. ANS: True. 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; 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 = int.Parse(Console.ReadLine()); Self-Review Exercises 3 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# app" on one line in the console window. ANS: Console.WriteLine("This is a C# app"); f) Display "This is a C# app" 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#\napp"); g) Write a statement that uses string interpolation to display the sum of the variables x and y . Assume variables x and y of type int exist and already have values. ANS: Console.WriteLine($"The sum of {x} and {y} is {x + y}"); 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- ment. Correction: Remove the semicolon after the right parenthesis. [ Note : With the semi- colon, the output statement executes regardless of whether the condition in the if is true.] b) 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 app 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; 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 = int.Parse(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 = int.Parse(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 = int.Parse(Console.ReadLine());

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all