Computer Programming 1 Using C# by Fidel C. Romasanta Dezza Marie M. Magsino and Mindoro State College of Agriculture and Technology (MinSCAT) Calapan City Campus All rights reserved. No part of this book may be reproduced or used in any manner whatsoever without prior written permission of the authors except for the use of brief quotations in a book review. Cover Page designed: Mr. Leoben Lucero MINDORO STATE COLLEGE OF AGRICULTURE AND TECHNOLOGY Calapan City Campus Masipit, Calapan City, Oriental Mindoro 5200 Tel. No. (043) 286-7371 Table of Contents UNIT 1 INTRODUCTION TO PROGRAMMING CHAPTER 1: Computers and Programming Lesson 1. Computers ....................................................................................................... Lesson 2. Programming ................................................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 2: Algorithms Lesson 1. Input Process Output........................................................................................ Lesson 2. Divide and Conquer.......................................................................................... Lesson 3. Pseudocode ..................................................................................................... Lesson 4. Flowchart ......................................................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ UNIT 2 INTRODUCTION TO PROGRAMMING LANGUAGE CHAPTER 3: Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5 Chapter Test C# Overview Historical Background of C# ............................................................................ Programming Features of C# ........................................................................... The .Net Framework......................................................................................... C# Program Structure ...................................................................................... Compiling and Executing the Program .............................................................. ........................................................................................................................ CHAPTER 4: C# Data Types and Data Conversion Lesson 1 Integer Types ................................................................................................... Lesson 2 Real Floating-point Types................................................................................. Lesson 3 Boolean Type ................................................................................................... Lesson 4 String Types ..................................................................................................... Lesson 5 Object Type...................................................................................................... Lesson 6. Type Conversion..................................................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 5: Variables Lesson 1. Naming Variables ................................................................................................... Lesson 2. Defining Variables ................................................................................................... Lesson 3. Initializing Variables ................................................................................................ Lesson 4. Accepting Values from User .................................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 6: Operators Lesson 1 Arithmetic Operators ........................................................................................ Lesson 2 Relational Operators ........................................................................................ Lesson 3 Logical Operators ............................................................................................. Lesson 4 Bitwise Operators ............................................................................................. Lesson 5 Assignment Operators ...................................................................................... Lesson 6 Precedence ...................................................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ UNIT 3 CONTROL FLOW CHAPTER 7: Conditional If Statements Lesson 1 If statement ...................................................................................................... Lesson 2 If and Else ........................................................................................................ Lesson 3 Nested if and else statement ............................................................................ Lesson 4 Common Programming Errors .......................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 8: Conditional Switch Statement Lesson 1 Switch Statement ............................................................................................. Lesson 2 Nested Switch Statement ................................................................................. Lesson 3 Common Programming Errors .......................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 9: Loops Lesson 1 While................................................................................................................ Lesson 2 Do while ........................................................................................................... Lesson 3 For .................................................................................................................. Lesson 4 Common Programming Errors .......................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 10: Arrays Lesson 1 Arrays as Arguments ........................................................................................ Lesson 2 Array Initialization ............................................................................................. Lesson 3 Single Dimensional .......................................................................................... Lesson 4 Two-Dimensional ............................................................................................. Lesson 5 Common Programming Errors .......................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ CHAPTER 11: Lesson 1 Lesson 2 Modularity Using Functions What is a Function ........................................................................................... Types of Function............................................................................................. Lesson 3 Advantages of Function .................................................................................... Lesson 4 Function and Parameter Declarations ............................................................... Lesson 5 Returning a Single Value .................................................................................. Lesson 6 Returning Multiple Values ................................................................................. Lesson 7 Variable Scope ................................................................................................. Lesson 8 Variable Storage Category ............................................................................... Lesson 9 Common Programming Errors .......................................................................... Learning Activities .................................................................................................................. Chapter Test ........................................................................................................................ 1 Introduction to Programming CHAPTER 1: Computers and Programming CHAPTER 2: Algorithms CHAPTER 1 Computer Programming The term programming or computer programming refers to the process of making computer programs. Computer programs are created by the programmer with the help of programming languages. A programming language is a set of instructions consisting of rules, syntax, numerical and logical operators, and utility functions. Learning Outcomes At the end of this Chapter, the students must have: published a reflection paper about the programming language on a blog page; and created a professional quality portfolio covering the ten (10) popular mobile/desktop/web applications. Pretest MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. Write your answer to the space provided before each number. _______ 1. The physical parts of the computer are referred to as __________. a) hardware b) software c) the operating system d) tools _______ 2. The part of a computer that runs programs is called __________. a) RAM b) secondary storage c) main memory d) the CPU _______ 3. A video display is a(n) __________ device. a) output b) input c) secondary storage d) main memory _______ 4. The computer stores a program while the program is running, as well as the data that the program is working with, in __________. a) secondary storage b) the CPU c) main memory d) the microprocessor _______ 5. A type of memory that can hold data for long periods of time, even when there is no power to the computer, is called __________. a) RAM b) main memory c) secondary storage d) CPU storage Lesson 1 Computers What is Computer? is a an electronic device that can manipulates data according to a precise set of instructions. electronic machine that performs high-speed mathematical or logical. 1 A computer is a sophisticated electronic device that can perform a series of tasks according to a precise set of instructions. Electronic device that performs high-speed mathematical or logical operation. However, it is important to remember that it is still a device that cannot work alone. Computer needs instructions or series of instructions called computer program or program to follow. Program made by the programmer using programming languages. Programs are commonly referred to as software. Software is essential to a computer because it controls everything the computer does. All of the software that we use to make our computers useful is created by individuals working as programmers or software developers. A programmer, or software developer, is a person with the training and skills necessary to design, create, and test computer programs. Computer programming is an exciting and rewarding career. In other words, programmers, programming languages, and computer programs has a vital role in today's technology. Computer Hardware and Software The physical parts of the computer that you can touch (tangible) are referred to as the computer’s hardware. The programs that execute on a computer are referred to as software. Hardware The term hardware refers to all of the physical parts, that a computer is made of. A computer is not one single device, but a system of devices that all work together. Each part in a computer plays its own part. As shown in Figure 1.2, a typical computer system consists of the following major components: The central processing unit (CPU) Main memory Secondary storage devices Input devices Output devices Figure 1.2 Components of Computer System CPU The central processing unit (CPU) is the most important component of the computer because it is the part of a computer that actually runs programs. The CPU is a small chip know as microprocessor. Main Memory This is where the computer stores a program being executed, as well as the data currently being processed. For instance, you are using word processing program (ex.: Microsoft Word) to write an essay for your classes. While you do this, both the Microsoft Word and the essay are stored in main memory. Main memory also known as random-access memory, or RAM. It is called this because the CPU is able to quickly access data stored at any random location in RAM. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. Meaning all data stored in RAM will be erased when the computer is turned off. Input Devices The component that send data to the computer is called an input device. Common input devices are the keyboard, mouse, scanner, microphone, and digital camera. Output Device Output is any information (processed data) the computer produces for people or for other devices. It might be a student grades, a list of names, sales report, income statement, etc. The data is sent to an output device. Common output devices are video displays, printers and speakers. Secondary Memory Secondary storage commonly know as auxiliary storage is a type of memory that can hold data for long periods of time, even when there is no power to the computer. Programs and important data are normally stored in secondary memory and loaded into main memory as needed. The most common type of secondary storage device is the hard disk drive (HDD). A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a disk drive mounted inside their case. Compact disc (CD), digital versatile disc (DVD), universal serial bus (USB) flash drive, and memory card are also popular for data storage. Software Software refers to set of electronic instructions that tell the hardware what to do. These sets of instructions are also known as programs, and each of them has a specific purpose. Programs that make computers active. In computer science, software are classified into two categories: System software System software refers to the program that control and manage the basic operations of a computer. System software typically includes the following types of programs: Operating System is the most fundamental set of programs on a computer. The most important piece of software in computer is the operating system because it controls the computer and its peripheral devices (hardware), and allows other programs to run on the computer. Figure 1.3 shows screens from three popular operating systems: Windows 10, Mac OS X, and Linux. Utility Program performs a specialized task that enhances the computer’s operation or safeguards data. Examples of utility programs are virus scanners, file compression programs, and data backup programs. Software Development Tools are the programs that programmers use to create, modify, and test software. Assemblers, compilers, and interpreters are examples of programs that fall into this category. Figure 1.3 Screens from the Windows, Mac OS X, and Ubunto Linux operating systems Windows 10 Mac OS X Note: A Photo of Windows 10. https://www.extremetech.com/ computing/260311-take-screenshot-windows. Copyright 2018 by Joel Hruska Note: A Photo of Mac OS X. https://appleinsider.com/articles/07/10/25/ extensive_mac_os_x_10_5_leopard_screenshot_gallery. Copyright 2008 by AppleInsider Staff Ubuntu Linux Note: A Photo of Ubuntu Linux. https://sea.pcmag.com/linux-reviews-and-pricecomparisons-from-pc-magazi/28816/ubuntu-linux-18-bionic-beaver. Copyright 2020 by Ben Moore Application software Application software helps computer users to solve problems or carry out everyday tasks. Programs that people normally spend most of their time running on their computers. Commonly used application software are word processing, desktop publishing software, spreadsheets, database, graphics, communication, web browsers, and game programs. Lesson 2 Programming Computer Programming Computer programming is an act of writing computer programs by computer programmer using programming language. Computer Programmer Computer programmer also know as software developer is a person who can write computer programs or who can do computer programming. Programming Language A programming language is a software use to develop computer programs, scripts, or other sets of instructions for computers to execute. The following are few of the programming languages: Types of Language: Machine Language. Machine language is the language understood by the computer because it is defined by the hardware of the computer. Each instruction or command is a collection of zeros and ones called binary (Ex.: 0101 1000 0101 1001 1100 0111). For that reason machine language is the hardest language for a person to understand, but it is the only language understood by the computer. All computer programs must be converted/translated into machine language. Assembly/Low-Level Language. Assembly language uses English-like abbreviations to represent operations performed on the data. It uses short mnemonic codes for instructions and allows the programmer to introduce names for blocks of memory that hold data. A program written in assembly language must be translated into machine language with the help of the special program called an assembler. Sample Assembly code: MOV TOTAL, 48 ADD MARKS, 10 MOV AL, 10 High-Level Language. A high-level language uses English-like instructions and common mathematical notations. High-level language allows programmers to create powerful and complex programs without knowing how the CPU works. As a result, it is easy and not timeconsuming to create a program in high-level language. Before it can be executed by computer, the program must be changed to machine code before executed. For high level language interpreter or compiler will translate the source code into object code. List of well-known highlevel programming languages is shown in Table 1.1. Table 1.1 Language Ada BASIC FORTRAN Programming Languages Description Ada was created in the 1970s, primarily for applications used by the U.S. Department of Defense. The language is named in honor of Countess Ada Lovelace, an influential and historic figure in the field of computing. Beginners All-purpose Symbolic Instruction Code is a general-purpose language that was originally designed in the early 1960s to be simple enough for beginners to learn. Today, there are many different versions of BASIC. FORmula TRANslator was the first high-level programming language. It was designed in the COBOL Pascal C and C++ C# Java Python Ruby Visual Basic 1950s for performing complex mathematical calculations. Common Business-Oriented Language was created in the 1950s, and was designed for business applications. Pascal was created in 1970, and was originally designed for teaching programming. The language was named in honor of the mathematician, physicist, and philosopher Blaise Pascal. C and C++ (pronounced “c plus plus”) are powerful, general-purpose languages developed at Bell Laboratories. The C language was created in 1972 and the C++ language was created in 1983. Pronounced “c sharp.” This language was created by Microsoft around the year 2000 for developing applications based on the Microsoft .NET platform. Java was created by Sun Microsystems in the early 1990s. It can be used to develop programs that run on a single computer or over the Internet from a web server. Python, the language we use in this book, is a general-purpose language created in the early 1990s. It has become popular in business and academic applications. Ruby is a general-purpose language that was created in the 1990s. It is increasingly becoming a popular language for programs that run on web servers. Visual Basic (commonly known as VB) is a Microsoft programming language and software development environment that allows programmers to create Windows based applications quickly. VB was originally created in the early 1990s. Compiler A compiler is program that converts the instruction of a high level language into machine language as a whole. A program written in high level language is called source code. The compiled version of the source code is called an object or executable program and can then be executed as many times as needed. Interpreter An interpreter is a program that converts one statement of a program at a time. It executes this statement before translating the next statement of the source program. If there is an error in the statement, the interpreter will stop working and displays an error message. Figure 1.4 Programming Cycle Generally there are five (5) steps in Programming Cycle. 1. Defining the problem – defining what has to be done or what problem has to be solved 2. Planning the solution – select the best method for solving the problem 3. Coding the solution – prepare the set of instructions for the computer to execute 4. Checking out the program – perform debugging and testing the program using representative input data 5. Documentation – write up the full specifications for other program users Learning Activities Activity 1: Reflection Paper Writing and Publishing Directions: Trace the development of any programing language and give your insights regarding the highlights of the development. Use the space below as your draft. Publish this writing in a blog page (see sample at this link: https://tinyurl.com/y5xngthe). For video tutorial on how to do blogging, you may click this link: https://youtu.be/YIr_0x1OzKs. Submit your work to google class on or before the date as reflected in in your study schedule. See Rubric in Blogging in the classwork. . . . Activity 2: Programming Language Portfolio Directions: Directions: Create a professional quality photography portfolio covering the ten popular mobile/ desktop applications. Submit your work on our google class on or before the date as reflected in on your study schedule. See Rubric in Portfolio Development in the classwork. Amazing! You may now take the assessment. If you have not completed the task, or you have difficulty in accomplishing the activity, please send me a message to our google class or you may ask clarifications through a text message or phone calls on the contact number included in your course guide. Chapter Test GENERAL RULES: Write your answer to the space provided before each number. I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. _______ 1. What group of programming languages is easiest for the computer to understand? a) The machine languages b) The high-level languages c) The low-level languages d) The human languages _______ 2. Which of the following is true of interpreted programs? a) All statements are translated then executed. b) Each statement is translated and executed before the next statement. c) Source code is translated into machine language as a whole then executed. d) All of these _______ 3. Before a program written in a high-level language can be executed, which of the following must take place? a) A program must be interpreted. b) A program must be compiled. c) A & B d) A program can be executed immediately. _______ 4. Which of the following is true of the interpreter? a) It translates instructions written in assembly language into machine language. b) It translates machine language into a high-level language. c) It translates a high-level language into machine language. d) All of these _______ 5. A(n) __________ is a set of instructions that a computer follows to perform a task. a) compiler b) program c) interpreter d) programming language _______ 6. The physical devices that a computer is made of are referred to as __________. a) hardware b) software c) the operating system d) tools _______ 7. The part of a computer that runs programs is called __________. a) RAM b) secondary storage c) main memory d) the CPU _______ 8. Today, CPUs are small chips known as __________. a) microcontrollers b) microprocessors c) memory chips d) operating systems _______ 9. The computer stores a program while the program is running, as well as the data that the program is working with, in __________. a) secondary storage b) the CPU c) main memory d) the microprocessor _______ 10. This is a volatile type of memory that is used only for temporary storage while a program is running. a) RAM b) secondary storage c) the hard disk drive d) the USB drive _______ 11. A type of memory that can hold data for long periods of time, even when there is no power to the computer, is called __________. a) RAM b) main memory c) secondary storage d) CPU storage _______ 12. A component that collects data from computer users and sends it to the computer is called __________. a) output devices b) input devices c) secondary storage devices d) main memory _______ 13. A video display is a(n) __________ device. a) output b) input c) secondary storage d) main memory _______ 14. A __________ is enough memory to store a letter of the alphabet or a small number. a) byte b) bit c) switch d) transistor _______ 15. A byte is made up of eight __________. a) CPUs b) instructions c) variables d) bits _______ 16. In a(n) __________ numbering system, all numeric values are written as sequences of 0s and 1s. a) hexadecimal b) binary c) octal d) decimal _______ 17. A bit that is turned off represents the following value: __________. a) 1 b) –1 c) 0 d) “no” _______ 18. Computers can only execute programs that are written in __________. a) Java b) assembly language c) machine language d) C# _______ 19. The __________ translates an assembly language program to a machine language program. a) assembler b) compiler c) translator d) interpreter _______ 20. A(n) __________ file is the compiled version of a high-level language program. a) assembler b) object c) source code d) binary II – TRUE or FALSE: Write T if the statement is true, otherwise write F. _______ 1. Today, CPUs are huge devices made of electrical and mechanical components such as vacuum tubes and switches. _______ 2. Main memory is also known as RAM. _______ 3. Any piece of data that is stored in a computer’s memory must be stored as a binary number. _______ 4. Images, like the ones you make with your digital camera, cannot be stored as binary numbers. _______ 5. Machine language is the only language that a CPU understands. _______ 6. Assembly language is considered a high-level language. _______ 7. An interpreter is a program that both translates and executes the instructions in a high-level language program. _______ 8. A syntax error does not prevent a program from being compiled and executed. _______ 9. Windows, Linux, and Mac OSX are all examples of application software. _______ 10. Word processing programs, spreadsheet programs, email programs, web browsers, and games are all examples of utility programs. III – IDENTIFICATION: Identify the answer in the following questions. _________________ 1. What is the most important component in a computer? _________________ 2. What number does a bit that is turned on represent? _________________ 3. What number does a bit that is turned off represent? _________________ 4. What would you call a device that works with binary data? _________________ 5. What type of programming language is this code 0010 0000 1110 0110 0000 0001 ? _________________ 6. What are the short words that are used in assembly language called? _________________ 7. What type of software controls the internal operations of the computer’s hardware? _________________ 8. What type of programming language is this code ADD AX, 0010 ? _________________ 9. What type of programming language is this code AREA = LENGTH * WIDTH; ? _________________ 10. What do we call a program written in high level language? CHAPTER 2 Algorithms In mathematics and computer science, an algorithm is a step-by-step procedure to solve a problem or to perform a task. One of the most obvious examples of an algorithm is a recipe. Learning Outcomes At the end of this Chapter, the students must have: analyzed problems and defined the computing requirements appropriate to its solution; analyzed user needs and take them into account in the selection, creation, evaluation and administration of computer-based systems; and created a portfolio covering the types of algorithm. Pretest MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. Write your answer to the space provided before each number. _______ 1. What is an algorithm? a) A chart showing the flow of a series of events b) A decision arrived at by following instructions c) Step-by-step instructions used to solve a problem d) A computer program that follows a chart _______ 2. If something needs to be processed what flowchart symbol do we use? a) oval b) rectangle c) parallelogram d) diamond _______ 3. What shape in the flowchart represents a decision? a) rectangle b) diamond c) oval d) parallelogram _______ 4. What does an oval represent in a flowchart? a) decision making b) start c) stop d) process _______ 5. In a flowchart how are symbols connected? a) Symbols do not get connected together in a flowchart b) With lines and an arrow to show the direction of flow c) With dashed lines and numbers d) With solid lines to link events Lesson 1 Input-Process-Output (IPO) Input-Process-Output (IPO) model, is a widely used approach in systems analysis and software engineering for describing the structure of an information processing program or other process. Figure 2.1 IPO model A computer program or any other sort of process using the input-process-output model receives inputs from a user or other source, does some computations on the inputs, and returns the results of the computations. The system divides the work into three categories: 1. input - data that is needed to solve the problem 2. process - the task that will be carried out to solve the problem 3. output - the end result of the problem For example, a program might be written to compute the price of apples if the quantity in kg and price per kg are given. Following the IPO model, the program must: Ask the user for the weight (quantity in kg) of apple and price per kilogram (input) Perform a calculation to compute the total price of apple (process) Display the total price (output) Quantity PricePerKilo Price = Quantity * PricePerKilo Price Second example, compute the sum of three numbers, the program must: Ask the user for the three number (input) Perform a calculation to compute the sum (process) Display the sum (output) Num1 Num2 Num3 Sum = Num1 + Num2 + Num3 Sum Third example, compute the area of a rectangle, the program must: Ask the user for the length and width (input) Perform a calculation to compute the area (process) Display the area (output) Length Width Area = Length * Width Area Exercises Write the IPO algorithm of the following problems: Compute and print the area and perimeter of the square using the given side. Write a program to calculate the average grade of three students. Convert Fahrenheit temperatures into Celsius temperatures. Convert kilogram into pounds. Convert meter into inch. Convert kilometer into mile. Calculate the car park charges: The 1st three hours costs ₱20.00. The subsequent hours cost ₱5.00 per hour. Write an algorithm based on a vehicle’s entry and exit time. Lesson 2 Divide and Conquer A divide-and-conquer algorithm works by recursively breaking down a problem into two or more subproblems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem (shown in Figure 2.2). Figure 2.2 Divide and Conquer Diagram Divide - break the given problem into smaller sub-problems. Conquer - Solve the smaller sub-problems. If the sub-problem is small enough, then solve it directly. Combine - Merge the solutions of the sub-problems to get the solution to the actual or original problem. Sample Task: Prepare a Breakfast Step 1: 1. Start 2. Prepare a Breakfast 3. End Step 2: 1. Start 2. Prepare a Breakfast 2.1 Prepare a tuna sandwich 2.2 Prepare some chips 2.3 Make a cup of coffee 3. End Step 3: 1. Start 2. Prepare a Breakfast 2.1 Prepare a tuna sandwich 2.1.1 Take 2 slices of bread 2.1.2 Prepare tuna paste 2.2 Prepare some chips 2.3 Make a cup of coffee 3. End Step 4: 1. Start 2. Prepare a Breakfast 2.1 Prepare a tuna sandwich 2.1.1 Take 2 slices of bread 2.1.2 Prepare tuna paste 2.2 Prepare some chips 2.2.1 Cut potatoes into slices 2.2.2 Fry the potatoes 2.3 Make a cup of coffee 3. End Step 5: 1. Start 2. Prepare a Breakfast 2.1. Prepare a tuna sandwich 2.1.1 Take 2 slices of bread 2.1.2 Prepare tuna paste 2.2. Prepare some chips 2.2.1 Cut potatoes into slices 2.2.2 Fry the potatoes 2.3. Make a cup of coffee 2.3.1 Boil water 2.3.2 Add water, sugar and coffee 3. End For example, a program might be written to sort an array using the divide and conquer approach. Given array Divide the array into two halves Again, divide each subpart recursively into two halves until you get individual elements. Then, merge the individual elements in a sorted manner. Here, conquer and combine steps go side by side. Lesson 3 Pseudocode Pseudocode is an outline of a program, written in a form that can easily be converted into real programming statements. It resembles the actual program that will be implemented later. However, it cannot be compiled nor executed. Pseudocode normally codes the following actions: Initialization of variables Assignment of values to the variables Arithmetic operations Relational operations For example, a program might be written to compute the price of apples if the quantity in kg and price per kg are given. The program must: Ask the user for the weight (quantity in kg) of apple and price per kilogram (input) Perform a calculation to compute the total price of apple (process) Display the total price (output) a. Start b. Read Quantity c. Read PricePerKg d. Price = Quantity * PricePerKg e. Print Price f. End Second example, compute the sum of three numbers, the program must: Ask the user for the three number (input) Perform a calculation to compute the sum (process) Display the sum (output) a. Start b. Read N1 c. Read N2 d. Read N3 e. Sum = N1 + N2 + N3 f. Print Sum g. End Third example, compute the area of a rectangle, the program must: Ask the user for the length and width (input) Perform a calculation to compute the area (process) Display the area (output) a. Start b. Read Length c. Read Width d. Area = Length * Width e. Print Area f. End Exercises Write the Pseudocode of the following problems: Compute and print the area and perimeter of the square using the given side. Write a program to calculate the average grade of three students. Convert Fahrenheit temperatures into Celsius temperatures. Convert kilogram into pounds. Convert meter into inch. Convert kilometer into mile. Calculate the car park charges: The 1st three hours costs ₱20.00. The subsequent hours cost ₱5.00 per hour. Write an algorithm based on a vehicle’s entry and exit time. Lesson 4 Flowchart A flowchart is a diagram representing the logical sequence in which a combination of steps or operations is to be performed. It consists of labeled geometrical symbols that are interconnected. representation of an algorithm. It is intended for communication and documentation. It is also a visual Flowchart Symbols: Terminal Symbol (oval) – use to designate the beginning and the end of the program. Input/output Symbol (parallelogram) – represents an instruction to an input or an output device. Processing Symbol (rectangle) – represent a group of program instructions that perform a processing function of the program such as to perform arithmetic operations. Decision Symbol (diamond) – denotes a point in the program where more than one path can be taken. Preparation Symbol (hexagon) – represent an instruction or group of instructions that will alter, or modify a program’s course of execution. It is commonly used to specify operations such as control, index register, initialization, switch setting, and in indicating loops. On-page Connector (small circle) – a none processing symbol use to connect one part of a flowchart to another without drawing flow lines. Off-page Connector (small pentagon) – to designate entry to or exit from a page when a flowchart requires more than one page. Flow Direction Indicators (arrowheads) – use to show the direction of processing or data flow. These are added to flow lines if a flowchart appears confusing is its layout. Arrowheads are not required when the logic flow is from top to bottom or from left to right. Flow lines (horizontal/vertical lines) – use to show reading order or sequence in which flowchart symbols are to be read. Flow lines are sometimes drawn with arrowheads. The commonly accepted practice is to indicate an arrowhead if the logic flow is from right to left or from bottom to top. Table 2.1 Arithmetic and Relational Operators Arithmetic Operators Relational Operators OPERATORS MEANING OPERATORS MEANING + Addition < Less than - Subtraction > Greater than * Multiplication = Equal / Division ≤ Less than or equal Div Division integer ≥ Greater than or equal Mod Modulus (remainder) ≠ Not equal For example, a program might be written to compute the price of apples if the quantity in kg and price per kg are given. The program must: Ask the user for the weight (quantity in kg) of apple and price per kilogram (input) Perform a calculation to compute the total price of apple (process) Display the total price (output) Figure 2.3 Simple Flowchart START READ Quantity START Note: You can combine inputs into one symbol. Use comma to separate two or more variables READ Quantity, PricePerKg READ PricePerKg Price = Quantity * PricePerKg Price = Quantity * PricePerKg PRINT Price PRINT Price END END Second example, compute the sum of three numbers, the program must: Ask the user for the three number (input) Perform a calculation to compute the sum (process) Display the sum (output) START Compute the Area of a rectangle START READ N1, N2, N3 Sum = N1 + N2 + N3 PRINT Sum N1 = 11 N2 = 4 N3 = 7 Area = 11 + 4 + 7 = 22 22 END END Third example, compute the area of a rectangle, the program must: Ask the user for the length and width (input) Perform a calculation to compute the area (process) Display the area (output) Compute the Area of a rectangle START START Length = 10 Width = 5 READ Length, Width Area = 10 * 5 = 50 Area = Length * Width 50 PRINT Area END END Exercises Draw the flowchart of the following problems: Compute and print the area and perimeter of the square using the given side. Write a program to calculate the average grade of three students. Convert Fahrenheit temperatures into Celsius temperatures. Convert kilogram into pounds. Convert meter into inch. Convert kilometer into mile. Calculate the car park charges: The 1st three hours costs ₱20.00. The subsequent hours cost ₱5.00 per hour. Write an algorithm based on a vehicle’s entry and exit time. Flowchart with Decision For example, a program might be written to accept grade and print “FAILED” if grade is less than 75, otherwise print “PASSED”. The program must: Ask the user for the grade (input) Display “FAILED” if grade is less than 75, otherwise display “PASSED” (process and output) START PASSED or FAILED START READ Grade Grade = 87 PRINT “PASSED” NO Is Grade < 75 ? YES No PRINT “FAILED” PASSED END If the inputted grade is 87, then the remarks will be PASSED. 87 < 75 END You can also use the on-page connector (small circle) to connect one part of a flowchart to another instead of a long flow line. . START READ Grade PRINT “PASSED” NO Is Grade < 75 ? YES PRINT “FAILED” A A END Second example, draw a flowchart to get a number from the user and print whether it is positive or negative, the program must: Ask the user for a number If a number is less than zero then print “NEGATIVE”, otherwise print “POSITIVE”. START READ Num PRINT “POSITIVE” NO Is Num < 0 ? YES PRINT “NEGATIVE” A A END Third example, draw a flowchart to get a number from the user and print whether it is even or odd, the program must: Ask the user for a number If a number divided by 2 is zero remainder then print “EVEN”, otherwise print “ODD”. START READ Num PRINT “ODD” NO Is Num mod 2=0? YES PRINT “EVEN” A A END Forth example, draw a flowchart to get two numbers from the user and print the smaller number, the program must: Ask the user for the two numbers If first number is less than the second number, print the value of first number, otherwise print the value of the second number. START READ N1, N2 PRINT N2 NO Is N1 < N2 ? YES PRINT N1 A A END Exercises Draw the flowchart of the following problems: Take three numbers from the user and print the biggest number. Takes a year from user and print whether that year is a leap year or not. Takes an age from the user and print whether the age is minor or adult. Minor age is below 18. Calculate the car park charges: The 1st three hours costs ₱20.00. The subsequent hours cost ₱10.00 per hour. Write an algorithm based on a vehicle’s entry and exit time. Flowchart with Loop Loop – a sequence of steps to be executed a specified number of times. Counter – is set up in a program loop to keep track of the number of times the program segment is repeated. For example, make a flowchart the will print numbers 1 to 20 Step 1: Start Step 2: C=1, initialization of counter Step 3: Yes, C is less than or equal to 20 Step 4: Print the value of C Step 5: C = C + 1, value of counter will increase by 1 Step 6: Go to Step 3 Step 7: No, C is not less than or equal to 20 Step 8: End END START C=1 A NO IS C<=20 ? YES PRINT C C=C+1 A Second example, compute and print the sum of numbers 1 to 20 Step 1: Start Step 2: C=1, initialization of counter Step 3: Sum = 0, initialization of sum Step 4: Yes, C is less than or equal to 20 Step 5: Sum = Sum + C, add the value of the counter to the sum Step 6: C = C + 1, value of counter will increase by 1 Step 7: Go to Step 4 Step 8: No, C is not less than or equal to 20 Step 9: Print the value of Sum Step 10: End START C=1 Sum = 0 A PRINT Sum NO IS C<=20 ? YES END Sum = Sum + C C=C+1 A Exercises Draw the flowchart of the following problems: Take ten numbers from the user and print the biggest number. Compute and print the sum of all even and all odd numbers of numbers 1 to 10. Print the smallest and the largest number in ten (10) inputted integers. Determine if the inputted integer is a prime number or not. Compute and print the average grade of fifty (50) students. Learning Activities Activity 1: Algorithms Portfolio Directions: Create a portfolio covering all lesson activities in the algorithm. Amazing! You may now take the assessment. If you have not completed the task, or you have difficulty in accomplishing the activity, please send me a message to our google class or you may ask clarifications through a text message or phone calls on the contact number included in your course guide. Chapter Test GENERAL RULES: Write your answer to the space provided before each number. I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. _______ 1. List of instruction for carrying out some process step by step. a) algorithms b) Interpreter c) Compiler d) pseudocode _______ 2. What is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem? a) Algorithms b) Flowchart c) Programming d) Pseudocode _______ 3. What shape do flowcharts begin with? a) rectangle b) oval c) diamond d) parallelogram _______ 4. What shape do flowcharts use to show an output? a) rectangle b) oval c) diamond d) parallelogram _______ 5. What shape do flowcharts use to show a decision? a) rectangle b) oval c) diamond d) parallelogram _______ 6. What shape do flowcharts use to show an action or process? a) rectangle b) oval c) diamond d) parallelogram _______ 7. What shape do flowcharts use to show an input? a) rectangle b) oval c) diamond d) parallelogram _______ 8. What shape do flowcharts end with? a) rectangle b) oval c) diamond d) parallelogram _______ 9. It is a visual representation of an algorithm. a) interpreter b) flowchart c) pseudocode d) compiler _______ 10. What is the purpose of flow lines and arrowheads in flowchart? a) Represents when something is input into the program or output from the program b) Asks a question and then determines which route the program will take c) An action done by the program (e.g. calculate the area of a square) d) Shows the direction and sequence of processes _______ 11. A benefit of using flowcharts is ________. a) They help you program faster b) They write the program for you c) They help you visualize the instructions d) They are easier _______ 12. What is the purpose of terminal symbol? a) Indicates the beginning or end of the flowchart b) Indicates an action or step in the flowchart process. c) A subroutine by user request, where the user is able to request info d) Indicates that the program has a save function. _______ 13. Which of the following is incorrect? Algorithms can be represented: a) as pseudo codes b) as syntax c) as programs d) as flowcharts _______ 14. In a flowchart how are symbols connected? a) Symbols do not get connected together in a flowchart b) With lines and an arrow to show the direction of flow c) With dashed lines and numbers d) With solid lines to link events _______ 15. When can algorithms be used? a) Only with computers b) Only when programming c) Only with flowcharts d) Any time to design solutions to problems II – TRUE or FALSE: Write T if the statement is true, otherwise write F. _______ 1. Algorithm refers to a special method usable for the solution to a problem. _______ 2. We can show the sequence of steps in an algorithm in a structural diagram called a flow chart. _______ 3. Only top software programmers can write an algorithm. _______ 4. When you write an algorithm the order of the instructions is very important. _______ 5. Any algorithm is a program. 2 Introduction to C# Programming CHAPTER 3: C# Overview CHAPTER 4: C# Data Types and Data Conversion CHAPTER 5: Variables CHAPTER 6: Operators CHAPTER 3 C# Overview C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). Learning Outcomes . At the end of this Chapter, the students must have: applied the basic structure of programming language; and created a program with basic input and output C# commands Pretest MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. Write your answer to the space provided before each number. __________ 1. Who is the development team leader of the C# programming language? a) Dennis Ritchie b) Anders Hejlsberg c) Martin Richards d) Ken Thompson __________ 2. Who is the development team leader of the C language? a) Dennis Ritchie b) Anders Hejlsberg c) Martin Richards d) Ken Thompson __________ 3. Who is the developer of the B language? a) Dennis Ritchie b) Anders Hejlsberg c) Martin Richards d) Ken Thompson __________ 4. Using , we can create applications that run on Windows. a) .NET Framework b) Xamarin c) .NET Core d) Compiler __________ 5. Using , we can create applications that run on Windows, Linux, and Mac a) .NET Framework b) Xamarin c) .NET Core d) Compiler Lesson 1 Historical Background C# (pronounced see-sharp) was developed by Microsoft within its .NET framework initiative and later approved as a standard by ECMA (ECMA-334) and International Standards Organization (ISO). The C# programming language is general-purpose object-oriented programming (OOP). C# development team was lead by "Anders Hejlsberg" in 2002. C evolved from two previous programming languages, B and BCPL. Martin Richards developed BCPL in 1967 designed mainly for writing operating systems and compilers. Ken Thompson developed B, modeled on BCPL, and early versions of the UNIX operating system were developed in this language in 1970 at Bell Laboratories. Dennis Ritchie evolved the C language from B at Bell Laboratories in 1972. UNIX was developed in C and most major operating systems today are also developed in C. During the 70s C continues to evolve and in 1978 Kernighan and Ritchie published one of the most widely-read computer books of all time, namely, The C Programming Language. C was extremely portable and provided much more powerful features than either BCPL or B. Figure 3.1 History of C# C# is based on C Language and C++ but has many additional extensions. Java and C# are both being updated to keep up with each other. Cross-development with Visual Basic, Visual C++, F#, IronPython, and many other .NET languages. Figure 3.2 shows the history of .NET Framework. Figure 3.2 History of .NET Framework Note: A Photo of .NET Framework History. https://codingsight.com/asp-net-core-1-0-part-1-introduction-general-description-future-net-framework/. Copyright 2016 by Karen Tazayan .NET Framework The .NET framework is a revolutionary platform that helps you to write the following types of applications: Windows applications Web applications Web services The .NET framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other. The .NET framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .NET framework: Common Language Runtime (CLR) The .Net Framework Class Library Common Language Specification Common Type System Metadata and Assemblies Windows Forms ASP.Net and ASP.Net AJAX ADO.Net Windows Workflow Foundation (WF) Windows Presentation Foundation Windows Communication Foundation (WCF) LINQ Figure 3.3 .NET Framework Today Note: A Photo of .NET Framework Today. https://codingsight.com/asp-net-core-1-0-part-1-introduction-general-description-future-netframework/. Copyright 2016 by Karen Tazayan In Figure 3.3 shows that: using .NET Framework, we can create mobile, desktop, and web applications that run on Windows PCs, devices and servers. using .NET Core, we can create applications that run on Windows, Linux, and Mac. using Xamarin we can create native Android, iOS, and Windows apps, using existing .NET skills. Strong Programming Features of C# Although C# constructs closely follow traditional high-level languages, C and C++ and being an objectoriented programming language. It has strong resemblance with Java, it has numerous strong programming features that make it endearing to a number of programmers worldwide. Following is the list of few important features of C#: Boolean Conditions Automatic Garbage Collection Standard Library Assembly Versioning Properties and Events Delegates and Events Management Easy-to-use Generics Indexers Conditional Compilation Simple Multithreading LINQ and Lambda Expressions Integration with Windows Integrated Development Environment (IDE) for C# Microsoft provides the following development tools for C# programming: Visual Studio Subscription (with pay) Professional Edition Enterprise Edition Visual Studio Community Edition (shown in Figure 3.4) Visual Studio Community (Windows OS) Visual Studio Code (Windows, LINUX, Mac OS) Figure 3.4 Visual Studio Community for Mac Download page for Visual Studio Community Edition Note: A Photo of Download page for Visual Studio Community Edition. https://visualstudio.microsoft.com/free-developer-offers/. You need an active internet connection for installing the community edition. The Visual Studio Community Edition is freely available from Microsoft official website. Using these tool, you can write all kinds of C# programs from simple command-line applications to more complex applications. You can also write C# source code files using a basic text editor like Notepad, and compile the code into assemblies using the command-line compiler, which is again a part of the .NET Framework. You can download it from Microsoft Visual Studio. It gets installed automatically on your machine. Writing C# Programs on Linux or Mac OS Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Visual Studio Code and Visual Studio Community for Mac are free version of the Visual Studio which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS. Kindly check Visual Studio Code and Visual Studio Community for Mac. Lesson 2 Installing of C# If you have already installed Visual Studio 2019 and C#, you can skip this section. If you haven’t installed C#, this section tells you how to download and install the Visual Studio. Visual Studio Community is a modified version that is available from Microsoft at no charge. Although the Community version of Visual Studio is missing some features found in the commercial version, you could compile and run all the sample programs in this book using Visual Studio. Software and Hardware Requirements At present time, the Visual Studio 2019 can be installed in the following operating system (OS 64 bit recommended ) : Software requirements: Windows 7 SP1 (with latest Windows Updates): Home Premium, Professional, Enterprise, Ultimate Windows Server 2012 R2 (with Update 2919355): Essentials, Standard, Datacenter Windows 8.1 (with Update 2919355): Core, Professional, and Enterprise Windows Server 2016: Standard and Datacenter Windows Server 2019: Standard and Datacenter Windows 10 version 1703 or higher: Home, Professional, Education, and Enterprise (LTSC and S are not supported) Hardware requirements: 1.8 GHz or faster processor. Quad-core or better recommended 2 GB of RAM; 8 GB of RAM recommended (2.5 GB minimum if running on a virtual machine) Hard disk space: Minimum of 800MB up to 210 GB of available space, depending on features installed; typical installations require 20-50 GB of free space. Hard disk speed: to improve performance, install Windows and Visual Studio on a solid-state drive (SSD). Video card that supports a minimum display resolution of 720p (1280 by 720); Visual Studio will work best at a resolution of WXGA (1366 by 768) or higher. Downloading Visual Studio At the time that this book is written, you can go to https://visualstudio.microsoft.com/free-developer-offers/ to download the Community version (shown in Figure 1.3) or go to https://visualstudio.microsoft.com/vs/pricing/ to download paid version (Professional and Enterprise) of Visual Studio. The installation page should look similar to what is shown in Figure 3.5. Figure 3.5 Visual Studio Installer Depending upon the speed of your system and Internet connection, it can take more than 1 hour to download and install the 6+ gigabytes of files used during the installation process. By continuing to install Visual Studio means, you agree to the License Agreement for the Visual Studio edition you selected. The program displays a dialog box that tells you the items that are about to be installed. Unless you are constrained by disk space, you should leave all the options checked so that they are all installed. Otherwise, you can uncheck those options that you do not want to be installed. See Figure 3.6. Figure 3.6 Installation Item Checklist Having made your selections, click the Install button to initiate the installation process. Your display will look similar to Figure 3.7. Figure 3.7 Installation Process Lesson 3 Program Structure Creating a Project Move the cursor to the upper-left side of the screen, and select the File ► New ► Project menu option from the main program menu bar, as shown in Figure 3.8. Figure 3.8 Creating New Project Select New Project from the menu. Your program screen changes, as shown in Figure 3.9. Figure 3.9 shows a number of predefined project templates from which to choose. Make sure you have selected the Templates Visual C# Windows menu option that appears on the left side of the screen. These templates define the types of programs that you can develop with C#. For this purposes, select the Console Application template. Figure 3.9 New Project Dialog When you select one of the templates, Visual Studio creates that type of project for you as well as writing some stub code for you. Stub codes are predefined pieces of code that Visual Studio writes for you as a background process. From the templates shown in Figure 1.8, select the Console Application template. You should also type in the name you want the program to have. Type HelloWorld for the example and designated the project to be placed in the C:\User\delfi\source\repos. You can use the Browse button to select some other directory, or you can click the Create button as shown in Figure 3.10. Figure 3.10 Name and Location of the Project Click Browse button to change project location. Creating Hello World Program A C# program consists of the following parts: Namespace declaration A class Class methods Class attributes A Main method Statements and Expressions Comments Figure 3.11 HelloWorld Console Application using System; namespace HelloWorld { class Program { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World!"); Console.ReadKey(); } } } When Figure 3.11 code is compiled and executed, it produces the following result: Hello World! Let us look at the various parts of the given program shown in Figure 3.11: The first line of the program using System; - the using keyword is used to include the System namespace in the program. An instruction that we may want to use one or more objects defined in the System namespace. A program generally has multiple using statements. The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorld namespace contains the class HelloWorld. The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main. The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. The next line /*...*/ is ignored by the compiler and it is put to add comments in the program. Programs usually contain comments. Multiple line comments are enclosed between a starting /* and an ending */. The compiler ignores anything between these two markers. Single line comments are preceded by //. Comments are a very important part of programming and you should generously comment your programs. The Main method specifies its behavior with the statement Console.WriteLine("Hello World!"); WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen. The last line Console.ReadKey(); is for the Visual Studio.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET. It is worth to note the following points: C# is case sensitive. All statements and expressions must end with a semicolon (;). The program execution starts at the Main method. Unlike Java, the program file name could be different from the class name. Lesson 4 Compiling and Executing the Program If you are using Visual Studio IDE for compiling and executing C# programs, take the following steps: Click Debug ►Start Debugging or Run button or press F5 key to execute the project as shown in Figure 3.12. A Command Prompt window appears that contains the line Hello World. Figure 3.12 Compiling and Executing the Program Lesson 5 Basic Syntax of Input and Output Commands C# User Input You have already learned that Console.WriteLine() is used to output (display) values. Now we will use Console.ReadLine() to get user input. In the following example, the user can input his or her name, which is stored in the variable yourName. Then we print the value of yourName: using System; namespace HelloName { class Program { static void Main(string[] args) { // my second program in C# Console.WriteLine("Enter your Name: "); /* Create a string variable and get user input from the keyboard and store it in the variable */ String yourName = Console.ReadLine(); // Display the value of variable yourName Console.WriteLine(“Hello “ + yourName); Console.ReadKey(); } } } Console.WriteLine(“Hello “ + yourName); or you can use Console.WriteLine with placeholder {sequence number} Console.WriteLine(“Hello {0}, have a nice day“, yourName); User Input and Numbers The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int. The following program will cause an error: Cannot implicitly convert type 'string' to 'int' like what is shown in Figure 3.13. using System; namespace HelloName { class Program { static void Main(string[] args) { // User input and number Console.WriteLine("Enter your age: "); int age = Console.ReadLine(); Console.WriteLine(“You're {0} years old now.", age); Console.ReadKey(); } } } Figure 3.13 Sample Program Error Syntax error with red line. Error message when mouse hover on error command. You must convert your input string into integer. You can convert any type explicitly, by using one of the Convert.To methods: using System; namespace HelloName { class Program { static void Main(string[] args) { // User input and number Console.WriteLine("Enter your age: "); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(“You're {0} years old now.", age); Console.ReadKey(); } } } Learning Activities Activity 1: Programming Portfolio 1. Write a program to print the following message on the screen: This is my first C# Program. Add a few blank lines before and after the message (hint: use "\n"). 2. Write a program to print your initial: 3. Write a program that will accept the first name, middle name and last name, then print the full name. Amazing! You may now take the assessment. If you have not completed the task, or you have difficulty in accomplishing the activity, please send me a message to our google class or you may ask clarifications through a text message or phone calls on the contact number included in your course guide. Chapter Test GENERAL RULES: Write your answer to the space provided before each number. I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. _______ 1. Who is the developer of C language? a) Dennis Ritchie b) Brian Kernighan c) Martin Richards d) Ken Thompson _______ 2. Who is the inventor of B language. a) Brian Kernighan b) Martin Richards c) Ken Thompson d) Dennis Ritchie _______ 3. Using , we can create applications that run on Windows. a) .NET Framework b) Xamarin c) .NET Core d) Compiler _______ 4. Using , we can create applications that run on Windows, Linux, and Mac a) .NET Framework b) Xamarin c) .NET Core d) Compiler _______ 5. The method is used to get user input. a) WriteLine() b) Readline() c) Write() d) ReadLine() _______ 6. The method is used to display the string to the console. a) WriteLine() b) ReadLine() c) ReadKey() d) Writeline() _______ 7. Multiple line comments are enclosed between marks. . a) /** comments here… b) // comments here… c) *// comments here… d) /* comments here …*/ _______ 8. What punctuation must each command line have at the end of the line? a) : (colon) b) , (coma) c) ! (exclamation point) d) ; (semicolon) _______ 9. The C# programming language is a) case-sensitive b) it depends c) not case-sensitive d) none of these _______ 10. Who is the developer of BCPL language. a) Brian Kernighan b) Martin Richards c) Ken Thompson d) Dennis Ritchie . II – TRUE or FALSE: Write T if the statement is true, otherwise write F. _______ 1. A syntax error does not prevent a program from being compiled and executed. _______ 2. Single line comments are preceded by //. _______ 3. C# development team was lead by Anders Hejlsberg in 2002. _______ 4. Using .NET Core, we can create native Android, iOS, and Windows apps. _______ 5. Just press F5 key to execute the C# project. CHAPTER 4 C# Data Types and Data Conversion Data is the fundamental currency of the computer. All computer processing deals with analysis, manipulation and processing of data. Data is entered, stored and retrieved from computers. Learning Outcomes . At the end of this Chapter, the students must have: described and differentiated data types used in C# created a program with type conversions and character and string manipulation. Pretest MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. Write your answer to the space provided before each number. _______ 1. When a variable must contain a whole number, assign the type . a) int b) short c) long d) All of these _______ 2. According to the C# specification, what are the respective sizes (in bytes) of the following three data types: short; int; and long? a) 1, 2, 4 b) 1, 2, 8 c) 2, 2, 4 d) 2, 4, 8 _______ 3. When a data type must contain fraction numbers, assign the type . a) int b) double c) char d) long _______ 4. This method removes all leading and trailing whitespaces of the string. a) Trim() b) TrimStart() c) TrimEnd() d) All of these _______ 5. This method returns the uppercase letter of a string. a) IsLower() b) ToLower() c) ToUpper() d) IsUpper() Lesson 1 Integer Types An integer data type is any numeric value expressed as a whole number. Integer values cannot have a fractional component associated with them. Table 4.1 lists the various integer data types that you can use in your programs. Table 4.1 Integer Data Types TYPE SPECIFIER BITS RANGE DATA byte 8 0 through 255 sbyte 8 -128 through 127 short 16 -32, 768 through 32,767 ushort 16 0 through 65,535 int 32 -2,147,483,648 through 2,147,483,647 uint 32 0 through 4,294,967,295 U, u long 64 -9,223,372,036,854,775,808 through L, l ulong 64 0 through 18,446,744,073,709,551,615 UL, ul As shown in Table 4.1, some data types are prefixed with the letter “s” (sbyte) while others are prefixed with the letter “u”. The “s” means the data are signed quantities (meaning minimum range, while the “u” means they are unsigned quantities. You can use sizeof(datatype) method to get the exact storage size (in byte) of the object or type. Following is an example to get the size of int type: using System; namespace dataSize { class Program { static void Main(string[] args) { // Display the size of data type in byte Console.WriteLine("Size of int: {0}", sizeof(int)); Console.ReadKey(); } } } Lesson 2 Floating-point Types A floating-point data type is any numeric value expressed as a fraction number. Table 4.2 lists the various floating-point data types that you can use in your programs. As shown in Table 4.2, each C# type keyword from the leftmost column is an alias for the corresponding .NET type. They are interchangeable. For example, the following declarations declare variables of the same type: double A = 12.3; System.Double B = 12.3; Table 4.2 TYPE SPECIFIER Floating-point Data Types BITS RANGE PRECISION DATA SUFFIX .NET Type decimal 128 -1.0 x 10-28 to 7.9228 x 1028 28-29 digits 0.0M System.Decimal double 64 5.0 x 10-324 to 1.7 x 10308 ~15-17 digits 0.0D System.Double float 32 -1.5 x 10-45 to 3.4 x 1038 ~6-9 digits 0.0F System.Single The decimal floating-point data type is appropriate for financial and monetary calculations because the decimal type has more precision and a smaller range than both float and double. Lesson 3 Boolean Type In C# the bool data type is a primitive data type having one of two values: true or false. This is a fundamental data type that is very common in computer programs. Very often, in programming, you will need a data type that can only have one of two values, like: YES / NO ON / OFF TRUE / FALSE For this, C# has a bool data type, which can take the values true or false. Table 4.3 Boolean Data Type TYPE SPECIFIER bool BITS 8 RANGE DATA SUFFIX true or false The bool type is the result type of comparison and equality operators. A bool expression can be a controlling conditional expression in the if, do, while, and for statements and in the conditional operator. Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9 Lesson 4 String Type The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes: string greeting = "Hello World"; Console.WriteLine(greeting); The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': char myGrade = 'B'; Console.WriteLine(myGrade); Table 4.4 Character and String Data Types TYPE SPECIFIER BITS RANGE char 16 single character surrounded by single quotes string string does not have sequence of characters (text) DATA SUFFIX '\0' string greeting = "Welcome to OOP"; Console.WriteLine(greeting); Lesson 5 Object Type The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. object obj; obj = 100; // this is boxing Lesson 6 Type Conversion Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms: Implicit type conversion - These conversions are performed by C# in a type safe manner. For example, conversions from smaller to larger integral types and conversions from derived classes to base classes. char ► int ► long ► float ► double Explicit type conversion - These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator. double ► float ► long ► int ► char Implicit casting is done automatically when passing a smaller size type to a larger size type: int myNumber = 9; double myDouble = myNumber; Console.WriteLine(myNumber); Console.WriteLine(myDouble); Console.ReadKey(); // Automatic casting: int to double // Outputs 9 // Outputs 9 Explicit casting must be done manually by placing the type in parentheses in front of the value: double myDouble = 99.99; int myNumber = (int)myDouble; Console.WriteLine(myDouble); Console.WriteLine(myNumber); Console.ReadKey(); // Manual casting: double to int // Outputs 99.99 // Outputs 99 C# Type Conversion Methods As shown in Table 4.5, C# has the following built-in type conversion methods: Table 4.5 C# Conversion Method METHODS DESCRIPTION ToBoolean Converts a type to a Boolean value, where possible. ToByte Converts a type to a byte. ToChar Converts a type to a single Unicode character, where possible. ToDateTime Converts a type (integer or string type) to date-time structures. ToDecimal Converts a floating point or integer type to a decimal type. ToDouble Converts a type to a double type. ToInt16 Converts a type to a 16-bit integer. ToInt32 Converts a type to a 32-bit integer. ToInt64 Converts a type to a 64-bit integer. ToSbyte Converts a type to a signed byte type. ToSingle Converts a type to a small floating point number. ToString Converts a type to a string. ToType Converts a type to a specified type. ToUInt16 Converts a type to an unsigned int type. ToUInt32 Converts a type to an unsigned long type. ToUInt64 Converts a type to an unsigned big integer. It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long): bool isPwd = false; int myInt = 99; double myDouble = 12545.245; Console.WriteLine(Convert.ToString(myInt)); // convert int to Console.WriteLine(Convert.ToDouble(myInt)); // convert int to Console.WriteLine(Convert.ToInt32(myDouble)); // convert double Console.WriteLine(Convert.ToString(isPwd)); // convert bool to Console.ReadKey(); string double to int string 99 99 12545 False Lesson 7 String Function A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the Length property: Table 4.6 Components of Computer System STRING FUNCTIONS DEFINITIONS SYNTAX AND EXAMPLES Contains() The C# Contains method checks whether specified character or string is exists or not in the string value. string.Contains(stringtoCheck); string mySkul=”MinSCAT”; Console.WriteLine (mySkul.Contains(“CAT”)); //OUTPUT: TRUE Console.WriteLine (mySkul.Contains(“cat”)); //OUTPUT: FALSE EndsWith() This EndsWith Method checks whether specified character is the last character of string or not. string.EndsWith(stringtoCheck); string mySkul=”MinSCAT”; Console.WriteLine (mySkul.EndsWith(“AT”)); //OUTPUT: TRUE Console.WriteLine (mySkul.EndsWith(“aT”)); //OUTPUT: FALSE IndexOf() Returns the index position of first occurrence of specified character. string mySkul = "MinSCAT"; Console.WriteLine(mySkul.IndexOf("A")); //OUTPUT: 5 Insert() Insert the string or character in the string at the specified position. Insert(int Indexvalue, string value); string s = "MCAT"; Console.WriteLine(s.Insert(1,"inS")); //OUTPUT: MinSCAT LastIndexOf() Returns the index position of last occurrence of specified character. LastIndexOf(string value); string s = "MinSCAT-Calapan"; Console.WriteLine(s.LastIndexOf("a")); //OUTPUT: 13 Length() It is a string property that returns length string mySkul=”MinSCAT”; int x=mySkul.Length; of string. string.Length; //value of x is equal to 7 This method deletes all the characters from beginning to specified index position. string.Remove(int StartIndex, [int count]); string s = "MinSCAT-Calapan City Campus"; Console.WriteLine(s.Remove(15,5)); //OUTPUT: MinSCAT Calapan Campus This method replaces the character. string.Replace(oldString, newString); string a=”I hate you”; Console.WriteLine(a.Replace(“hate”,”love”); //OUTPUT: I love you. Substring() This method returns substring. string.substring(int startingIndex, [int charLength]); string mySkul=”MinSCAT”; Console.WriteLine(mySkul.Substring(3)); //OUTPUT: SCAT Console.WriteLine(mySkul.Substring(1,4)); //OUTPUT: inSC ToLower() Converts String into lower case based on rules of the current culture. string.ToLower (); String mySkul=”MinSCAT”; Console.WriteLine(mySkul.ToLower()); //OUTPUT: minscat ToUpper() Converts String into Upper case based String mySkul=”MinSCAT”; Console.WriteLine(mySkul.ToUpper()); on rules of the current culture. Remove() Replace() string.ToUpper(); //OUTPUT: MINSCAT Trim It removes extra whitespaces from beginning and ending of string. string.Trim(); String mySkul=” MinSCAT ”; Console.WriteLine(mySkul.Trim()); //OUTPUT: MinSCAT Learning Activities Activity 1: Programming Portfolio 1. Write a program in C# to separate the individual characters from a string. Test Data Input the string : MinSCAT Output: M i n S C A T 2. Write a program in C# to print individual characters of the string in reverse order. Test Data Input the string: MinSCAT String in reverse order: TACSniM 3. Write a program in C# to count the total number of words in a string. Test Data Input the string : Welcome to MinSCAT Total number of words in the string is : 3 4. Write a program in C# count a total number of alphabets, digits and special characters in a string. Test Data Input the string : Welcome to ITE212 - Object-Oriented Programming Number of Alphabets in the string is : 37 Number of Digits in the string is : 3 Number of Special characters in the string is : 6 5. Write a program in C# to count a total number of vowel or consonant in a string. Test Data Input the string : Welcome to Object-Oriented Programming The total number of vowel in the string is : 13 The total number of consonant in the string is : 21 Amazing! You may now take the assessment. If you have not completed the task, or you have difficulty in accomplishing the activity, please send me a message to our google class or you may ask clarifications through a text message or phone calls on the contact number included in your course guide. Chapter Test General Rules: Write your answer to the space provided before each number. I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. _______ 1. When a variable must contain a whole number, assign the type a) short b) int c) long d) All of these _______ 2. According to the C# specification, what are the respective minimum sizes (in bytes) of the following three data types: short; int; and long? a) 1, 2, 4 b) 1, 2, 8 c) 2, 2, 4 d) 2, 4, 8 _______ 3. When a data type must contain fraction numbers, assign the type a) int b) double c) char d) long _______ 4. Which of the following convert expression to integer type in C#? a) int.Parse b) Convert.ToInt32 c) A & B d) All of these _______ 5. Which of the following is an 8-byte Integer? a) char b) long c) short d) int _______ 6. Which of the following is NOT an Integer? a) char b) long c) short d) int _______ 7. Which of the following does not store a sign? a) short b) integer c) byte d) single _______ 8. Which of the following is the correct default value of a Boolean type? a) 0 b) 1 c) true d) false _______ 9. What kind of data will this variable store – char fName; ? a) a single character b) numeric c) text string d) true/false value _______ 10. What is the size of a char in C#? a) 4 bits b) 7 bits c) 16 bits d) 8 bits _______ 11. What will be the output of this code? string str = “You are awesome!!”; Console.WriteLine(str[9]); a) a b) e c) w d) error _______ 12. What will be the output of this code if you use the value of variable str in question #11. Console.Write(str.Substring(8, 8)); a) aweso b) awesome c) awesome! d) awesome!! _______ 13. What is the name of the process by which two or more strings are joined together? a) Concatenation b) Method c) Association d) Substring _______ 14. It returns the uppercase letter of a string. a) IsLower() b) ToLower() c) ToUpper() d) IsUpper() _______ 15. Removes all leading and trailing whitespaces of the string. a) Trim() b) TrimStart() c) TrimEnd() d) All of these CHAPTER 5 Variables A variable is a symbolic name for data or information. Each variable has a specific data type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable. Learning Outcomes . At the end of this Chapter, the students must have: Applied best practices in naming and declaring variables. created a program with variable manipulation. Pretest MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. Write your answer to the space provided before each number. _______ 1. In order to properly use a variable, . a) the variable must have a valid type b) the variable name must begin with a letter or underscore c) the variable name cannot be a keyword d) All of these _______ 2. When a variable must contain a whole number, assign the type a) int b) short c) long d) All of these _______ 3. Which of the following is correct about variable naming conventions in C#? a) A name must begin with a letter or underscore that could be followed by a sequence of letters, digits (0 - 9) or underscore. b) The first character in an identifier cannot be a digit. c) A & B d) None of the above. _______ 4. Which of the following C# declarations are invalid? a) byte edad; b) int sweldo; c) string yourName; d) double 1stSalary; _______ 5. Which of the following is a valid variable? a) TIN# b) ReadKey c) 2ndPrize d) sALaRy Lesson 1 Naming Variables A variable is simply a name you give to a specific piece of data. Back in the dark ages of programming, you might store an integer value at memory address 10,000. In those days there were no variable names. You simply typed in 10000 anytime you wanted to reference that integer value. It didn’t take long before programmers started writing programming tools that let them use symbolic names (such as operand1) for memory addresses, which made the act of writing programs much easier and less error prone, hence the advent of variable names. A variable name, also called an identifier, has several syntax rules you must follow to keep the Visual Studio compiler happy. These syntax rules are as follows: The first character must be a letter (a through z, A through Z) or an underscore (_). An identifier can consist of letters, numbers (0 - 9) and underscores only. Reserved words or keywords (e.g. words that already have a special purpose in the language such as int, char and double) cannot be used as variable names. Although it is not a rule, it is also a good idea to give variables meaningful names, but without overdoing it. Address1 is a better name than a1 even though Visual Studio accepts either name. A second convention, called camel notation, is that long variable names start with lowercase letters and that each following word in the name is capitalized, as in yourFirstName. Camel notation makes it easier to read the variable names. Example: int lengthOfTheRectangle; //bad double lengthRec; //good In addition, please note carefully that C# is case sensitive. For example, the identifiers Rate, rate and RATE are all considered to be different by the C# compiler. This is a common source of compiler error and programming error. Lesson 2 Defining Variables In C# before a variable can be used, it must be defined or declared. Declarations associate a specific data type with each variable that is declared, and this tells the compiler to set aside an appropriate amount of memory space to hold values associated with the variable. Syntax: <type> <variableName>; Example: string empName; double grossSalary, deduction, netSalary; In the first statement, only a single string variable empName was declared, whereas in the second statement three double variables were declared in one go. In this case, each variable must be separated from the other by a comma. Lesson 3 Initializing Variables Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is: Syntax: <variableName> = value; Example: string empName; double grossSalary, deduction, netSalary; empName = “Pedro dela Cruz”; grossSalary = 24000.00; deduction = 15230.77; netSalary = 8769.23; Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as: Syntax: <data_type> <variableName> = value; Example: string empName = “Pedro dela Cruz”; double grossSalary = 24000.00, deduction = 15230.77, netSalary = 8769.23; Lesson 4 Accepting Values from User The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable. Write a simple program that accepts three values (employee's name, gross salary, and deduction) from the keyboard and performs a mathematical operation to compute the net salary (net salary = gross salary - deduction). Console Application: using System; namespace UserInput { class Program { static void Main(string[] args) { string empName; double grossSalary, deduction, netSalary; Console.Write("Name: "); empName = Console.ReadLine(); Console.Write("Gross Salary: "); grossSalary = Convert.ToDouble(Console.ReadLine()); Console.Write("Deduction: "); deduction = Convert.ToDouble(Console.ReadLine()); netSalary = grossSalary - deduction; Console.WriteLine("Net Salary: " + netSalary); Console.ReadKey(); } } } Sample Output: Learning Activities Programming Portfolio: Solve the following problems using Console Application 1. Write a program to display the computed salary of the employee. Program should accept employee's name, number of hours worked, rate per hour, and deduction. Test Data Employee’s Name: Juan dela Paz Number of hours worked: 40 Rate per hour: 520.85 Deduction: 5400 Salary: 15434.00 2. Write a program to display student information and the computed tuition fee. Program should accept student’s name, ID Number, total number of units, tuition fee per unit. Test Data Student’s Name: Pedro Mendoza ID number: MCC2020-00001 Number of units: 24 Tuition per unit: 200 Tuition Fee: 4800 Amazing! You may now take the assessment. If you have not completed the task, or you have difficulty in accomplishing the activity, please send me a message to our google class or you may ask clarifications through a text message or phone calls on the contact number included in your course guide. Chapter Test General Rules: Write your answer to the space provided before each number. I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer. _______ 1. When a variable must contain a whole number, assign the type. a) long b) int c) short d) All of these _______ 2. In order to properly use a variable, . a) the variable must have a valid data type b) the variable name must begin with a letter or underscore c) the variable name cannot be a keyword d) All of these _______ 3. Which of the following is correct about variable naming conventions in C#? a) A name must begin with a letter or underscore that could be followed by a sequence of letters, digits (0 - 9) or underscore. b) The first character in an identifier cannot be a digit. c) A & B d) None of the above. _______ 4. Which of the following is an invalid C# declarations? a) byte age; b) int num; c) string yourName; d) double 1stSalary; _______ 5. Which of the following is an invalid C# variable ? a) IDnO b) $ALaRy c) Writeline d) my1stTime _______ 6. What kind of data will this variable store – char middleInitial; ? a) numeric b) Text c) a single character d) true/false value _______ 7. Which of the following is false? a) Variable values can change while a program runs b) Variables make it possible to process almost any kind of data c) All variables use the same amount of memory d) Variable values can be stored in a database or file. _______ 8. Which of the following is an invalid C# declarations? a) byte userAge; b) integer intScore; c) string strName; d) decimal netSalary; _______ 9. Which of the following is a method use to examine if data can be converted into another type of data? a) Parse b) Convert c) TryParse d) ConvertTo _______ 10. Naming convention in which the first letter of each word in a compound word is capitalized, except for the first word. a) Camel Case b) Lower Case c) Pascal Case d) Upper Case CHAPTER Learning Outcomes Pretest 6 Operators 3 Control Flow CHAPTER 7: Conditional If Statements CHAPTER 8: Conditional Switch Statement CHAPTER 9: Loops CHAPTER 10: Arrays CHAPTER 11: Modularity Using Functions CHAPTER Learning Outcomes Pretest 7 Conditional If Statements Blogging Rubric SCORE 2 4 6 10 Idea and Content The ideas expressed are not original, often confused, and are not connected to discussions around the subject matter. The ideas expressed are not necessarily original and are not usually connected to the discussion around the subject matter. The student expressed some original ideas. The majority of ideas are related to the subject matter. The student has many original ideas and expressed them clearly. The great majority of ideas are related to the subject matter. Post Frequency The post frequency is below course expectation. The post frequency is slightly below average. The post frequency is slightly above average. The post frequency greatly exceeds course expectations. Writing Quality The post show very poor quality. There is little to no evidence of reading other information in order to form new meaning of the topics at hand. The post show a below average, overly casual writing style with a lack of attention to style. Students pay little attention to other reading and mostly regurgitate previous personal views. The post show an above average writing style. The content demonstrates that the students read moderately, and attempts to synthesize information and form new meaning. The post is well written and characterized by elements of a strong writing style. The content demonstrates that the student is wellread, synthesizes learned content, and constructs new meaning. Community Students do not show evidence in any participation in the blogging community, or the course community, through the use of weblogs. Students rarely participated in the blogging community. Most, if not all, participation was limited to the weblogs of other classmates. The student participated moderately in the blogging community. There was some evidence of out-of-class participation. The student participated actively in the blogging community via comments on other weblogs, and citing others in their research and writing. The student did nothing to enhance or personalize the weblog space. There is very little evidence of multimedia enhancement and the student blog is primarily textbased. The student enhanced their weblog to some extent using video, audio, images, or other add-ons. The student greatly enhanced their weblog space using video, audio, images, or other add-ons. CRITERION Use of Enhancements MARK