أخر الاخبار

Chapter 1 in Programming Fundamentals 1

Chapter 1 in Programming Fundamentals 1


Chapter 1 in Programming Fundamentals 1



1- Introduction

Computer use is increasing in almost every field of endeavor. In an area of steadily rising costs, computing costs have decreased dramatically because of rapid developments in both hardware and software technology.

A computer is a device capable of performing computations and making logical decisions at speeds millions and even billions of times faster than those of human beings. For example, many of today’s personal computers can perform hundreds of millions—even billions—of additions per second. A person operating a desk calculator might require decades to complete the same number of calculations that a powerful personal computer can perform in one second. Trillion-instruction-per-second computers are already functioning in research laboratories! Computers process data under the control of sets of instructions called computer programs these programs guide computers through orderly sets of actions that are specified by individuals known as computer programmers.A computr is composed of various devices (such as the keyboard,screen, mouse , disk, memory, CD-ROM and processing units) known as hardware. The programs that run on a computer are referred to as software. Hardware costs have been declining dramatically in recent years, to the point that personal computers have become a commodity. Software development costs, however, have been rising steadily, as programmers develop ever more powerful and complex applications without being able to improve significantly the technology of software development.

 

2- Computer Organization

 

Virtually every computer, regardless of differences in physical appearance, can be envisioned as being divided into six logical units, or sections:

1.  Input unit. This “receiving” section of the computer obtains information (data and computer programs) from various input devices. The input unit then places this information at the disposal of the other units to facilitate the processing of the information. Today, most users enter information into computers via keyboards and mouse devices. Other input devices include microphones (for speaking to the computer), scanners (for scanning images) and digital cameras (for taking photographs and making videos).


2.   Output unit. This “shipping” section of the computer takes information that the computer has processed and places it on various output devices, making the information available for use outside the computer. Computers can output information in various ways, including displaying the output on screens, playing it on audio/ video devices, printing it on paper or using the output to control other devices.

3.  Memory unit. This is the rapid-access, relatively low-capacity “warehouse” section of the computer, which facilitates the temporary storage of data. The memory unit retains information that has been entered through the input unit, enabling that information to be immediately available for processing. In addition, the unit retains processed information until that information can be transmitted to output devices. Often, the memory unit is called either memory or primary memory— random access memory (RAM) is an example of primary memory. Primary memory is usually volatile, which means that it is erased when the machine is powered off.

4.   Arithmetic and logic unit (ALU). The ALU is the “manufacturing” section of the computer. It is responsible for the performance of calculations such as addition, subtraction, multiplication and division. It also contains decision mechanisms, allowing the computer to perform such tasks as determining whether two items stored in memory are equal.

5.  Central processing unit (CPU). The CPU serves as the “administrative” section of the computer. This is the computer’s coordinator, responsible for supervising the operation of the other sections.

6.   Secondary storage unit. This unit is the long-term, high-capacity “warehousing” section of the computer. Secondary storage devices, such as hard drives and disks, normally hold programs or data that other units are not actively using; the computer then can retrieve this information when it is needed—hours, days, months or even years later. Secondary storage is usually nonvolatile—it retains information even when the computer is off.

 

3-  Machine Languages, Assembly Languages and High-level Languages

 

Programmers write instructions in various programming languages, some directly understandable by computers and others that require intermediate translation steps. Although hundreds of computer languages are in use today, the diverse offerings can be divided into three general types:


1.  Machine languages

2.  Assembly languages

3.  High-level languages

Any computer can understand only its own machine language directly. As the “natural language” of a particular computer, machine language is defined by the computer’s hardware design. Machine languages generally consist of streams of numbers (ultimately reduced to 1s and 0s) that instruct computers how to perform their most elementary operations. Instead of using the strings of numbers that computers could directly understand, programmers began using English-like abbreviations to represent the elementary operations of the computer. These abbreviations formed the basis of assembly languages. Translator programs called assemblers convert assembly language programs to machine language at computer speeds. Although computer use increased rapidly with the advent of assembly languages, these languages still required many instructions to accomplish even the simplest tasks. To speed up the programming process, high-level languages, in which single statements accomplish substantial tasks, were developed. Translation programs called compilers convert high-level- language programs into machine language. High-level languages enable programmers to write instructions that look almost like everyday English and contain common mathematical notations.

 

4-  C Sharp Language (C#)

The C# programming language developed at Microsoft by a team and designed specifically for the .NET platform as a language that would enable programmers to migrate easily to .NET. This migration is made easy due to the fact that C# has roots in C, C++ and Java, adapting the best features of each and adding new features of its own. Because C# has been built upon such widely used and well-developed languages, programmers will find learning C# to be easy and enjoyable.

 

5-  Structured Programming

structured programming can be defined as approach to the creation of programs that are clear, demonstrably correct and easy to modify. One of the more tangible results of this research was the development of the Pascal programming language in 1971. Pascal, named after the seventeenth-century mathematician and


philosopher Blaise Pascal, was designed for teaching structured programming in academic environments and rapidly became the preferred introductory programming language in most universities. Unfortunately, because the language lacked many features needed to make it useful in commercial, industrial and government applications, it was not widely accepted in these environments. By contrast, C, which also arose from research on structured programming, did not have the limitations of Pascal, and programmers quickly adopted it.

 

6- Microsoft Visual Studio

Visual Studio .NET is Microsoft’s integrated development environment (IDE) for creating, documenting, running and debugging programs written in a variety of

.NET programming languages. Visual Studio .NET also offers editing tools for manipulating several types of files. Visual Studio .NET is a powerful and sophisticated tool for creating business-critical and mission-critical applications.

 

7- Simple Program: Printing a Line of Text

C# uses some notations that might appear strange to nonprogrammers. We begin by considering a simple program that displays a line of text. The program and its output are shown in figure (1) The program is followed by an output window that displays the program’s results. When you execute this program, the output will appear in a console window.

Figure (1) simple printing program


Figure (1) simple printing program


Line 1 begins with //, indicating that the remainder of the line is a comment. Programmers insert comments to document and improve the readability of their code. Comments also help other people read and understand your programs. This comment simply indicates the figure number and file name for this program. A comment that begins with // is called a single-line comment, because the comment terminates at the end of the line. Single-line comments can be placed almost anywhere in the program. There is also syntax for writing multiple-line comments. A multiple-line comment, such as

/* This is a multiple–line comment. It can be

split over many lines */

Begins with delimiter /* and ends with delimiter */. All text between these delimiters is treated as a comment and is ignored by the compiler. In the Visual Studio .NET IDE, all comment text appears in green. Comments of the form // and /* */ are ignored by the compiler; therefore, they do not cause the computer to perform any action when the program executes.

Line 4 (known as a using directive) is generated by the Visual Studio IDE and declares that the program uses features in the System namespace. A namespace groups various C# features into related categories. One of the great strengths of C# is that C# programmers can use the rich set of namespaces provided by the .NET framework. These namespaces contain code that programmers can reuse, rather than “reinventing the wheel.” This makes programming easier and faster. The namespaces that are defined in the .NET Framework contain preexisting code known as the .NET Framework Class Library. An example of one of the features in namespace System is Console, which we discuss momentarily. The various features are organized into namespaces that enable programmers to locate them easily.

Line 5 is a blank line. Programmers often use blank lines and space characters throughout a program to make the program easier to read. Collectively, blank lines, space characters, newline characters and tab characters are known as whitespace (space characters and tabs are known specifically as whitespace characters).

Lines 6–12 define our first class (these lines collectively are called a class definition). C# programs consist of pieces called classes, which are logical groupings of members (e.g., methods) that simplify program organization. These methods (which are like functions in procedural programming languages) perform tasks and return information


when the tasks are completed. A C# program consists of classes and methods created by the programmer and of preexisting classes found in the Framework Class Library.. Every program in C# consists of at least one class definition that the programmer defines. These classes are known as programmer-defined classes. The class keyword begins a class definition in C# and is followed immediately by the class name (Welcome1, in this example). Keywords (or reserved words) are reserved for use by C# and always consist of lowercase letters. By convention, each word in a class name begins with an uppercase first letter and has an uppercase letter for each word in the class name (e.g., SampleClassName). The name of the class is known as an identifier, which is a series of characters consisting of letters, digits, underscores ( _ ) and “at” symbols (@). Identifiers cannot begin with a digit and cannot contain spaces. Examples of valid identifiers are Welcome1, _value, m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space. The “at” character (@) can be used only as the first character in an identifier. C# is case sensitive—uppercase and lowercase letters are considered different letters, so a1 and A1 are different identifiers. Line 8 is present in all C# console and Windows applications. These applications begin executing at Main, which is known as the entry point of the program. The parentheses after Main indicate that Main is a program building block, called a method. C# class definitions normally contain one or more methods and C# applications contain one or more classes. For a C# console or Windows application, exactly one of those methods must be called Main, and it must be defined as shown on line 8; otherwise, the program is not executable. Normally, a console applications' Main method is defined as shown on line 8., Methods. For now, simply mimic Main’s first line in each C# application. The left brace ({) on line 9 begins the body of the method definition (the code which will be executed as a part of our program). A corresponding right brace (}) terminates the method definition’s body (line 11). Notice that the line in the body of the method is indented between these braces.

Line 10 instructs the computer to perform an action, namely, to print a series of characters contained between the double quotation marks. Characters delimited in this manner are called strings, character strings or string literals. We refer to characters between double quotation marks generically as strings. Whitespace characters in strings are significant—the compiler does not ignore these characters when they appear in strings. The Console class enables programs to output information to the computer’s


standard output. Class Console provides methods that allow C# programs to display strings and other types of information in the Windows command prompt. Method Console.WriteLine displays (or prints) a line of text in the console window. When Console.WriteLine completes its task, it positions the output cursor (the location where the next character will be displayed) at the beginning of the next line in the console window. (This is similar to pressing the Enter key when typing in a text editor—the cursor is repositioned at the beginning of the next line in the file.) The entire line, including Console.WriteLine, its argument in the parentheses ("Welcome to C# Programming!") and the semicolon (;), is called a statement. Every statement must end with a semicolon (known as the statement terminator). When this statement executes, it displays the message Welcome to C# programming! In the console window (Figure(1)). In C# statements we normally precede each class name with its namespace name and a period. For example, line 10 would normally be System.Console.WriteLine( "Welcome to C# Programming!" ); for the program to run correctly. The using directive on line 4 eliminates the need to specify explicitly the namespace System when using classes in the namespace. This can save time and confusion for programmers. To present the printing instruction a simple program is shown in figure (2).


 

Figure (2) Simple printing program

Figure (2) Simple printing program


A single statement can display multiple lines by using newline characters. Recall that these characters indicate when to position the output cursor at the beginning of the next line in the console window to continue output. Figure (3) demonstrates using newline characters. Line 10 produces four separate lines of text in the console window. Normally, the characters in a string are displayed exactly as they appear between the double quotes. However, notice that the two characters “\” and “n” do not appear on the screen. The backslash (\) is called an escape character. It indicates that a “special” character is to be output. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. This escape sequence \n is the newline character. It causes the cursor (i.e., the current screen position indicator) to move to the beginning of the next line in the console window. Some common escape sequences are listed in Figure (4).

 


Figure (3) Simple printing program using “\n”


 

 

Figure (3) Simple printing program using \n”


 

Escape sequence

Description

\n

Newline. Position the screen cursor to the beginning of the next line.

\t

Horizontal tab. Move the screen cursor to the next tab stop.

\r

Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.

\\

Backslash. Used to print a backslash character.

\"

Double quote. Used to print a double quote (") character.

 

Figure (4) Some common escape sequences

 

 

8-  Variables in C #

 

Variables are essentially locations in computer memory that are reserved for storing the data used by an application. Each variable is given a name by the programmer and assigned a value. The name assigned to the variable may then be used in the C# code to access the value assigned to the variable. This access can involve either reading the value of the variable, or changing the value. It is, of course, the ability to change the value of variables which gives them the name variable.

 

a-    C# Integer Variable Types

 

A variable must be declared as a particular type such as an integer, a character or a string. C# is what is known as a strongly typed language in that once a variable has been declared as a particular type it cannot subsequently be changed to a different type. While it is not possible to change the type of a variable it is possible to disguise the variable as another type under certain circumstances. Variable declarations require a type, a name and, optionally a value assignment. The table (1) shows the different types of integer variables


 

Type

Size in Bytes

Value Range

Byte

1 byte

0 to 255

Sbyte

1 byte

-128 to 127

Short

2 bytes

-32,768 to 32,767

Ushort

2 bytes

0 to 65,535

Int

4 bytes

-2,147,483,648 to 2,147,483,648

Uint

4 bytes

0 to 4,294,967,295

Long

8 bytes

-1020 to 1020

Ulong

8 bytes

0 to 2 x 1020

 

Table (1) the integer variable types

 

 

 

b-   C# Floating Point Variables

 

Integers are fine for dealing with whole numbers but of little use when there are numbers after the decimal point. Such numbers may be stored in float or double variable types. The default type for such numbers is double. The following table (2) shows the two types with comparisons of the number ranges supported and the number of significant digits in each case:

 

 

 

 

Type

Size in Bytes

Value Range

Digit Accuracy

Float

4 bytes

1.5 * 10-45 to 3.4 * 1038

6 - 7 digits

Double

8 bytes

5.0 * 10-324 to 1.7 * 10308

15 - 16 digits

 

Table (2) Floating Point Variables

 

It is important to note that float and double variables cannot be used as counting variables (for example in looping constructs).


c-    C# String Variables

 

In this language works for storing a single letter or number it is of little use for storing entire words or sentences. For this purpose the string variable type is supported by C#. Variables of type string can store a string of any number of characters. String values are surrounded by double quotes ("). For example:

 

string myString = "This is a string";

 

 

9-  C# Constant

 

A constant is similar to a variable in that it provides a named location in memory to store a data value. Constants differ in one significant way in that once a value has been assigned to a constant it cannot subsequently be changed. Constants are particularly useful if there is a value which is used repeatedly throughout the application code. Rather than use the value each time, it makes the code easier to read if the value is first assigned to a constant which is then referenced in the code. For example, it might not be clear to someone reading your C# code why you used the value 5 in an expression. If, instead of the value 5, you use a constant named interestRate the purpose of the value becomes much clearer. Constants also have the advantage that the if the programmer needs to change a widely used value it only needs to be changed once in the constant declaration and not each time it is referenced. As with variables, constants have a type, a name and a value. Unlike variables, constants must be initialized at the same time that they are declared and must be prefixed with the const keyword:

 

Simple Program: Adding Integers

Our next application (Figure ( 5)) inputs two integers (whole numbers) typed by a user at the keyboard, compute the sum of these values and displays the result. As the user types each integer and presses the Enter key, the integer is read into the program and added to the total. Lines 1–2 are single-line comments stating the figure number, file name and purpose of the program.

As stated previously, every C# program consists of at least one class definition. Line 6 begin the definition of class Addition. Lines 7–37 define the body of the class.


Recall that all class definitions start with an opening left brace ({) and end with a closing right brace (}).

 




 

Figure (5) program to adding two integers

Figure (5) program to adding two integers


 

Figure (5) program to adding two integers

 

 

You can eliminate the need for string variables firstNumber and secondNumber by combining the input and conversion operations as follows:

int number1;

number1 = Int32.Parse( Console.ReadLine() );

 

 

11- Programming Tools

Before writing a program to solve a problem, it is essential to have a through understanding of the problem and a carefully planned approach. When writing a program, it is equally essential to understand the types of building blocks that are available and to employ proven program construction principle. In this section and the next, we present the theory and principle of structured programming . The techniques you will learn are applicable.


1- The flowchart

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these boxes, and arrows connecting them represent flow of control. Data flows are not typically represented in a flowchart, in contrast with data flow diagrams; rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields. Figure (6 ) show the basic shapes used in flowchart,


Figure (6) the basic shapes of flowchart


Figure (6) the basic shapes of flowchart

 

 

2 The Algorithm

Any computing problem can be solved by executing a series of actions in a specific order .A procedure for solving a problem in terms of

1.  The actions to be executed and

2.  The order in which these actions are to be executed

Is called an algorithm. The example that follows demonstrates the importance of correctly specifying the order in which the actions are to be executed.

Consider the “rise-and-shine algorithm” followed by one junior executive for getting out of bed and going to work:


(1)   Get out of bed

(2)   Take off pajamas,

(3)   Take a shower

(4)   Get dressed

(5)   Eat breakfast

(6)   Carpool to work. This routine gets the executive to work well-prepared to make critical decisions.

 

Suppose that the same steps are performed in a slightly different order:

(1)   Get out of bed

(2)   Take off pajamas

(3)   get dressed

(4)   Take a shower

(5)   Eat breakfast

(6)   Carpool to work. In this case, our executive shows up for work soaking wet.


The importance of correctly specifying the order in which actions appear applies to computer programs, as well. Program control refers to the task of ordering a program’s statements correctly.

 

Ex1 Write an algorithm and draw flowchart for calculating age?

Sol:

        
Start

        Get year born

        Calculate age

        Print age

        If age > 50 print OLD

        End


Ex 2: Write an algorithm and draw a flowchart to add two numbers?

Sol:

The algorithm

        Start

        Get two numbers

        Add them

        Print the answer

                                                         

 

12- Memory Concepts

Variable names, such as number1, number2 and sum, actually correspond to locations in the computer’s memory. Every variable has a name, a type, a size and a value. In the addition program, the statement (line 26)

number1 = Int32.Parse( firstNumber );

16

 

Converts to an int the string that the user entered. This int is placed into a memory location to which the name number1 has been assigned by the compiler. Suppose the user enters the string 45 as the value for firstNumber. The program converts firstNumber to an int, and the computer places the integer value 45 into location number1, as shown

location number1




When a value is placed in a memory location, this value replaces the previous value in that location. The previous value is lost (or destroyed).

When the statement (line 27)

 

 

number2 = Int32.Parse( secondNumber );

executes, suppose the user types 72 as the value for secondNumber. The program converts secondNumber to an int, the computer places the integer value 72 into location number2 and memory appears as shown

 

location number2



 

Once the program has obtained values for number1 and number2, it adds these values and places their total into variable sumOfNumbers. The statement

 

sumOfNumbers = number1 + number2;

 

 

performs the addition and replaces (i.e., destroys) sum’s previous value. After calculating the sum, memory appears as shown. Note that the values of number1 and number2 appear exactly as they did before the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read from a memory location, the process is nondestructive.

 


values of number1 and number2



13-   Arithmetic Operations

Most programs perform arithmetic calculations. Table (3) below summarizes the arithmetic operators. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) represents the modulus operator. The arithmetic operators in table (3) are binary operators, because they each require two operands. For example, the expression sum + value contains the binary operator + and the two operands sum and value.

Table (3 ) the arithmetic operations


 

 

Table (3 ) the arithmetic operations

 

 

Integer division contains two int operands. The result of this computation is an integer quotient; for example, the expression 7 / 4 evaluates to 1 and the expression 17

/5 evaluates to 3. Note that any fractional part in integer division simply is discarded (i.e., truncated)—no rounding occurs. C# provides the modulus operator, %, which yields the remainder after integer division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. This operator is used most commonly with integer operands, but also can be used with other arithmetic types; we consider interesting applications of the modulus operator, such as determining whether one number is a multiple of another. There is no arithmetic operator for exponentiation in C#. Arithmetic expressions in C# must be written in straight-line form to facilitate entering programs into a computer. Thus, expressions such as “a divided by b must be written as a / b so that all constants, variables and operators


appear in a straight line. The following algebraic notation generally is not acceptable to compilers     .

C# expressions can use parentheses in the same manner as in algebraic expressions.

For example, to multiply a times the quantity b + c, we write

a * ( b + c )

C# applies the operators in arithmetic expressions in a precise sequence, determined by the following rules of operator precedence, which are generally the same as those followed in algebra:

 

1.  Operators in expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may be used to force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are at the highest level of precedence. With nested (or embedded) parentheses, the operators in the innermost pair of parentheses are applied first.

 

2.Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are applied from left to right. Multiplication, division and modulus are said to have the same level of precedence.

 

3.    Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction have the same level of precedence. The rules of operator precedence enable C# to apply operators in the correct order. When we say operators are applied from left to right, we are referring to the associativity of the operators. If there are multiple operators, each with the same precedence, the associativity determines the order in which the operators are applied. We will see that some operators associate from right to left. Table (4) summarizes the rules of operator precedence.


 

Table(4) the order of evaluation


Table(4) the order of evaluation

 

 

Notice in the chart that we make note of nested parentheses. Not all expressions with several pairs of parentheses contain nested parentheses. For example, the expression

a * ( b + c ) + c * ( d + e )

Has multiple sets of parentheses, but not nested parentheses. Rather, these parentheses are said to be “on the same level.” Let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its C# equivalent. The following is an example of an arithmetic mean (average) of five terms: Algebra:

 

 



 

C#: m = ( a + b + c + d + e ) / 5;

The parentheses are required because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as

 

𝑎 + 𝑏 + 𝑐 + 𝑑 + 𝑒

5


The following is the equation of a straight line:

 



 

C#: y = m * x + b;

 

 

No parentheses are required. The multiplication occurs first because multiplication has a higher precedence than addition. The assignment occurs last because it has a lower precedence than multiplication and division. The following example contains modulus (%), multiplication, division, addition and subtraction operations:

 

 



 

 

The circled numbers under the statement indicate the order in which C# applies the operators. The multiplication, modulus and division operators evaluate first in left-to- right order (i.e., they associate from left to right). The addition and subtraction evaluate next. These also are applied from left to right.

To develop a better understanding of the rules of operator precedence, consider how a second-degree polynomial (y = ax2 + bx + c) evaluates:

 



 

The circled numbers under the statement indicate the order in which C# applies the operators. There is no arithmetic operator for exponentiation in C#; x2 is represented as x * x. The .NET Framework Class Library provides method Math.Pow for exponentiation in C#.


Suppose a, b, c and x are initialized as follows: a = 2, b = 3, c = 7 and x = 5. In Figure below illustrates the order of evaluation of the operators. As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression easier to read. Unnecessary parentheses are also called redundant parentheses. For example, the preceding assignment statement might be parenthesized as

y = ( a * x * x ) + ( b * x ) + c;



 

table

table


 

14- Decision Making: Equality and Relational Operators

This section introduces C#’s if structure, which allows a program to make a decision based on the truth or falsity of some condition. If the condition is met (i.e., the condition is (true), the statement in the body of the if structure executes. If the condition is not met (i.e.,the condition is false), the body statement does not execute. Conditions in if structures can be formed by using the equality operators and relational operators, summarized in table (5). The relational operators all have the same level of precedence and associate from left to right. The equality operators both have the same level of


precedence, which is lower than the precedence of the relational operators. The equality operators also associate from left to right.

 


Table (5 ) Equality and relational operators


Table (5 ) Equality and relational operators

 

 

The next example uses six if statements to compare two numbers input into a program by the user. If the condition in any of these if statements is true, the assignment statement associated with that if executes. The user inputs values that the program converts to integers and stores in variables number1 and number2. The program compares the numbers and displays the results of the comparison in the command prompt. The program and sample outputs are shown in Figure (7).





Figure (7) Using equality and relational operators. (Part 1 of 2.)

Figure (7) Using equality and relational operators. (Part 1 of 2.)

Figure (7) Using equality and relational operators. (Part 1 of 2.)



 

Figure (7) Using equality and relational operators. (Part 1 of 2.)

 

 

Math Class Methods

Math class methods allow the programmer to perform certain common mathematical calculations. We use various Math class methods to introduce the concept of methods in general. We discuss many other methods from the classes of the Framework Class Library.

Methods are called by writing the name of the method, followed by a left parenthesis,

 

the argument (or a comma-separated list of arguments) of the method and a right parenthesis. The parentheses may be empty, if we are calling a method that needs no information to perform its task. For example, a programmer wishing to calculate and print the square root of 900.0 might write

Console.WriteLine( Math.Sqrt( 900.0 ) );

When this statement executes, the method Math.Sqrt calculates the square root of the number in parentheses (900.0). The number 900.0 is the argument to the Math.Sqrt method. The Math.Sqrt method takes an argument of type double and returns a result of type double. The preceding statement uses the result of method Math.Sqrt as the argument to method Console.WriteLine and displays 30.0. Note that all Math class

methods must be invoked by preceding the method name with the class name Math and a dot (.) operator (also called the member access operator).

It is not necessary to add an assembly reference to use the Math class methods in a program.


Class Math is located in namespace System, which is available to every program.

 

Forgetting to invoke a Math class method by preceding the method name with the class name Math and a dot operator (.) results in a syntax error.

Method arguments may be constants, variables or expressions. If c1 = 13.0, d= 3.0

and f = 4.0, then the statement

Console.WriteLine( Math.Sqrt( c1 + d * f ) );

calculates and displays the square root of 13.0 + 3.0 * 4.0 = 25.0, which is 5.0. Figure below summarizes some Math class methods. In this figure, the variables x

and y are of type double; however, many of the methods provide versions that take values of other data types as arguments. The Math class also defines two commonly used mathematical constants

Math.PI (3.14159265358979323846) and Math.E (2.7182818284590452354).

The constant Math.PI of class Math is the ratio of a circle’s circumference to its diameter.

The constant Math.E is the base value for natural logarithms (calculated with the

Math.Log method).


 

 

Figure (7) Using equality and relational operators. (Part 1 of 2.)


pictrue

pictrue

pictrue



EXERCISES

 

1-  Given y = ax3 + 7, which of the following are correct statements for this equation?

a) y = a * x * x * x + 7;

b) y = a * x * x * ( x + 7 );

c) y = ( a * x ) * x * ( x + 7 );

d) y = ( a * x ) * x * x + 7;

e) y = a * ( x * x * x ) + 7;

f) y = a * x * ( x * x + 7 );

 

2-    Indicate the order of evaluation of the operators in each of the following C# statements, and show the value of x after each statement is performed.

a) x = 7 + 3 * 6 / 2 - 1;

b) x = 2 % 2 + 2 * 2 - 2 / 2;

c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );

 

 

3-  Write an application that displays the numbers 1 to 4 on the same line with each pair of adjacent numbers separated by one space. Write the program using the following methods:

a)  Use one Console.Write statement.

b)  Use four Console.Write statements.

 

 

4-  Write an application that asks the user to enter two numbers, obtains the two numbers from the user and prints the sum, product, difference and quotient of the two numbers.

 

5-  Write an application that inputs from the user the radius of a circle and prints the circle’s diameter, circumference and area. Use the following formulas (r is the radius): diameter = 2r, circumference = 2πr, area = πr2.


6-  Write an application that displays in the console window a box, an oval, an arrow and a diamond, using asterisks (*) as follows:

 

*********                                                                   ***                                       *                   *

*              *                                                                 *        *                                  ***                 * *

*              *                                                               *            *                              *****                   * *

*              *                                                               *            *                                  *                      * *

*              *                                                               *            *                                  *                *                                                               *

*              *                                                               *            *                                  *                      * *

*              *                                                               *            *                                  *                       * *

*              *                                                                 *         *                                   *                   * *

*********                                                                   ***                                       *                   *

 

7-    What does the following code print?

Console.WriteLine( "*\n**\n***\n****\n*****" );

 

 

8-    What does the following code print?

Console.Write( "*" ); Console.Write( "***" ); Console.WriteLine( "*****" ); Console.Write( "****" ); Console.WriteLine( "**" );

9-    Write an application that reads in two integers and determines and prints whether the first is a multiple of the second. For example, if the user inputs 15 and 3, the first number is a multiple of the second. If the user inputs 2 and 4, the first number is not a multiple of the second. [Hint: Use the modulus operator.]

 

10 - Write algorithm and Draw a flowchart to print number from   1 to 15 ?

11-  Write algorithm and Draw a flowchart to find the sum of odd numbers from 1 to 100?

12-  Write algorithm and Draw a flowchart to find Y

 

2

 

+

 

3

 

n

 

Y = X2            X 3 + ... + X n

 

13-  Write algorithm and Draw a flowchart to find area of rectangle?

14-    Write algorithm and Draw a flowchart to test number odd or even ?

15-    Write algorithm and Draw a flowchart to find the mult numbers from 1 to 100 16- Write algorithm and Draw a flowchart to find the value of S from

S = 3 + 6 + 9 + …+ 30


17-       Write    algorithm    and    draw    flow    chart    to    find    the             value           of      Z

Z = 5( f (X ) - 2g(X )) where

 


f ( X ) =            ,    g( X ) = X 2 - 4

 

18-    Write algorithm and draw flow chart to find value of X from:

 

 

 

a + b

if

I = 1

a – b

if

I = 2

X=      a* b

if

I = 3

a/ b

if

I = 4

 

 

 

19-   
Draw a flowchart to find the largest of three numbers A,B, and C.

20-  write algorithm and draw flow chart to print odd number from 35 to 55? 21- Draw a flowchart for computing factorial N (N!) where N!=1*2*3*….*N.

تعليقات



حجم الخط
+
16
-
تباعد السطور
+
2
-