chapter 2

18
1 2.0 PROGRAMME DESIGN 2.1 Know Operators And Expressions 2.1.1 Explain the operand and operator. As we have seen, a mathematics expression can be made up of only one element, for example, a number, as in: 3 The above expression evaluates to three. This value of three can be represented by the number 3. Usually, though, expressions are much more involved than the simple one above. Let's consider this one: 3 + 2 The above expression evaluates to five. The above expression has three elements in it: The number 3 The addition operator '+' The number 2 Well, we have already dealt with the idea that 2 and 3 are numbers representing values in an expression. Here, let's talk about the '+'. Officially, the '+' in the above expression is called an operator. It is the addition operator. Operators do not exist alone in expressions. That is, for example, the addition operator needs some values to add. It needs some values to operate upon. In this expression: 3 + 2 The addition operator works with, or operates upon, the values represented by the numbers 3 and 2. The numbers 3 and 2 are said to be the operands for the '+', that is, the 3 and the 2 are operands for the addition operator. It is very handy to think of the addition operator as 'grabbing' the 3 and the 2 and, through arithmetic, producing a value of five.

Upload: fotress-dazelz

Post on 21-Jul-2016

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 2

1

2.0 PROGRAMME DESIGN 2.1 Know Operators And Expressions

2.1.1 Explain the operand and operator.

As we have seen, a mathematics expression can be made up of only one element, for example, a number, as in:

3

The above expression evaluates to three. This value of three can be represented by the

number 3.

Usually, though, expressions are much more involved than the simple one above. Let's

consider this one:

3 + 2

The above expression evaluates to five.

The above expression has three elements in it:

The number 3 The addition operator '+'

The number 2

Well, we have already dealt with the idea that 2 and 3 are numbers representing values

in an expression. Here, let's talk about the '+'.

Officially, the '+' in the above expression is called an operator. It is the addition operator.

Operators do not exist alone in expressions. That is, for example, the addition operator

needs some values to add. It needs some values to operate upon.

In this expression:

3 + 2

The addition operator works with, or operates upon, the values represented by the numbers 3 and 2. The numbers 3 and 2 are said to be the operands for the '+', that is,

the 3 and the 2 are operands for the addition operator.

It is very handy to think of the addition operator as 'grabbing' the 3 and the 2 and,

through arithmetic, producing a value of five.

Page 2: Chapter 2

2

Speaking a bit more technically, we would say that the above expression evaluates to five because the addition operator operates on the 3 and the 2, (the number 3 and the

number 2 are its operands), to produce a value of five.

So, now we know:

Mathematics expressions are made up of operators and operands. When an expression is evaluated operators accept operands, (which are values),

and produce new values through arithmetic.

Specifically, regarding the addition operator we see:

The symbol for the addition operator is '+'. The addition operator needs two operands, one to its left and one to its right.

The operands for the addition operator are values.

Since the addition operator requires two operands, we say that it is a binary operator.

Binary means 'consisting of two parts'.

There are other binary operators present in expressions. There is also the subtraction

operator, as in:

7 - 4

Here, the subtraction operator, '-', accepts the 7 and the 4, and using arithmetic it

produces a value of three.

So, we now have two examples of binary operators in mathematics expressions:

The addition operator, '+'

The subtraction operator, '-'

Now, an expression can have several addition and subtraction operators in it. For

example:

7 - 4 + 2

The operators are going to accept values as operands, but in this case, which operator

gets the first turn at accepting these values, the '-' or the '+'?

To answer that question, it would be handy to know which operator is 'stronger'. In mathematics, when one operator is 'stronger' than another, we say that it has precedence over the other. That is, it precedes the other in the order of the steps taken

necessary to evaluate the expression.

Page 3: Chapter 2

3

As it turns out the addition operator and the subtraction operator have equal precedence, one is not 'stronger' than the other. In cases like this, when two operators

are of equal precedence, evaluation proceeds from left to right.

So, in this case the subtraction operator goes first since it is left most. In detail, here is

how this evaluation unfolds, starting with the original expression:

7 - 4 + 2

The '-' operator goes first. It accepts the value of seven represented by the number 7 and the value of four represented by the number 4, does arithmetic called subtraction,

and produces a value of three.

Since the value of three can be represented by the number 3, this work effectively

changes the above expression to look like this:

3 + 2

Now, the action is handed over to the '+' operator. It accepts the value of three, (which was handed to it by the '-' operator), and the value of two represented by the number 2,

does arithmetic called addition, and produces a value of five.

The value of five can be represented by the number 5, so the above expression boils

down to this one:

At this point we know:

In math expressions there are operators and operands. It is the interaction among operators and operands that is called the

evaluation of the expression. The evaluation of a mathematics expression produces a final value. Binary operators require two operands. The addition operator, '+', and the subtraction operator, '-', are both binary

operators. The addition operator and the subtraction operator have equal

precedence. When two operators have equal precedence, the one to the left accepts

operands first, producing a value which is passed over to the other

operator.

Page 4: Chapter 2

4

2.1.2 Describe the different types of operator: arithmetic, relational, logical, and Boolean operator

Arithmetic Operator

Operator name Syntax

Basic assignment a = b

Addition a + b

Subtraction a - b

Unary plus (integer promotion)

+a

Unary minus (additive inverse)

-a

Multiplication a * b

Division a / b

Modulo (remainder) a % b

Increment Prefix ++a

Suffix a++

Decrement Prefix --a

Suffix a--

Page 5: Chapter 2

5

Relational Operator

Operator name Syntax

Equal to a == b

Not equal to a != b

Greater than a > b

Less than a < b

Greater than or equal to a >= b

Less than or equal to a <= b

Logical Operator

Operator name Syntax

Logical negation (NOT)

!a

Logical AND a && b

Logical OR a || b

Page 6: Chapter 2

6

Boolean Operator

Operator name Syntax

Bitwise NOT ~a

Bitwise AND a & b

Bitwise OR a | b

Bitwise XOR a ^ b

Bitwise left shift[note 1] a << b

Bitwise right shift[note 1] a >> b

2.2 Understand Programme Flow Control Structures 2.2.1 Identify Programme Flow Control Structures.

Control flow is the determinant of the direction in program implementation. Beginning with the first command, control will determine the direction which will be held on until the program ends.

2.2.2 List the various types of logical structures.

There are three control structures that can be used in solving the problems there are sequence structure, selection and loop structures.

Page 7: Chapter 2

7

2.2.3 Explain the various types of logical structures. a. Sequence

Sequence structure is simple structure that directs the implementation of the program line by line in order. General form the structure of the sequence is as follows { Statement_1; …… Statement_n; }

b. Selection

The selection structure would be to use two types of statement whether the if-else or switchThere are 2 type for selection structure: 1.if. a. if b. if ..else c. if .. else if d. if / if .. else nested 2. switch and break. a. switch .. case.

c. Looping

Looping statement or repeat statement allows C is coded only once in the program but its implementation was repeated several times. The number of repetitions should be controlled so that the program can be terminated properly. There are two ways to control the replication, using counters or using sentinel data provided in the expression. Counters are used if the number of repetitions is known when the program code. Data Sentinel is used if the number of repetitions is not known when the program coded. Example fund = 2; while (fund <= 200) fund = 3 * fund

2.2.4 Describe the different types of selection structure. a. if, if..else, switch..case

if

if checks whether the value is true and if so, includes the code in “{“ until the closing “}” If not, that code is removed from the copy of the file given to the compiler prior to compilation (but it has no effect on the original source code file). There may be nested if

Page 8: Chapter 2

8

statements. It is common to comment out a block of code using the following construction because you cannot nest multi-line comments in C Example If (mark==‟A‟) printf (“pass\n”);

if ..else

If..else statement used for cases that provide a choice of two options to be implemented if the conditions are true and the other options to be implemented if the condition is false. Depending on the results of the expression conditions only one of two options wil l

be executed.

The general format for these are,

if( condition 1 ) statement1; else statement2;

switch .. case. Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. Example switch ( <variable> ) { case this-value: Code to execute if <variable> == this-value break; case that-value: Code to execute if <variable> == that-value break; ... default: Code to execute if <variable> does not equal the value following any of the cases break; }

Page 9: Chapter 2

9

b. Nested selection

When a selection structure‟s true path or its false path contains another selection structure, the inner selection structure is referred to as a nested selection structure Example if (early_reg)

{ if (teacher) Fee = 3000; else { If(group>=5) Fee = 2600; else Fee = 2800; } }

else { If(coporate) Fee = 3500; Else

Fee = 3100; }

2.2.5 Describe the different types of looping structures. a. For

Statement for allowing us to repeat certain parts of the program until a specified number of repetitions. This means that when we write a program, we can determine the required number of repetitions. Every time the loop, the statement for counting the number of repetitions to achieve a specified number of repetitions. After that statement after the for will be executed! General format for statement „for‟ for (prefix; test; update) statement; Prefix - an expression that assigns the initial value of loop counter.

Page 10: Chapter 2

10

Test - conditions that determine whether the end of the loop continues to loop or not. Updates - the expression to update the loop counter. Example for (bil = 1; bil <= 8; bil++) printf(“%d\t”,bil);

b. while, do.. while

while Structural repetition of the second control loop controlled conditions. This loop can be written as a while statement. While loop will loop until a certain condition is achieved. In fact while we do not need information on the number of loops, but just need to put conditions to continue to loop. When these conditions are not met, the loop will stop. General format for while statement while (expression) statement; Expression - the conditions of the loop controller that produces the value true or false. Statement - any statement that is due respect. Example total = i = 0; printf(“Enter one number bigger than 0”); scanf(“%d”, &n); while (i != n) { total += i; i ++; }

c. Nested looping

Nested looping occurs when there are two looping statements in one program. When nesting occurs, the fact that the loop will be implemented at all until the end of the loop at all times outside the loop. Example for (i = 0; i < 2; i++) {

Page 11: Chapter 2

11

for (j = 0; j < 5; j++) { printf(“%d, %d\t”, i, j); } printf(“\n”); }

2.3 Know Storing Information 2.3.1 Define a variable and a constant.

Variable

A variable is the storage location in memory that is stored by its value. A variable is identified or denoted by a variable name. The variable name is a sequence of one or more letters, digits or underscore, for example: character _

Constants

Constants have fixed value. Constants, like variables, contain data type. Integer constants are represented as decimal notation, octal notation, and hexadecimal notation. Decimal notation is represented with a number. Octal notation is represented with the number preceded by a zero character. A hexadecimal number is preceded with the characters 0x.

2.3.2 Describe the following basic data types: numeric, character,

string, logical.

Numeric Integer data type used to represent negative numbers or positive integers. For example, 77, 0, 999, +999. Tues memory size of type integer is different - depending on computer system.

Integer Data Type Byte Ranges short int 2 -32767 .. 32767

unsigned short int 2 0 .. 65535

int 2 -32767 .. 32767

unsigned int 2 0 .. 65535

long int 4 -2147483647 .. 2147483647

unsigned long int 4 0 .. 4294967295

Page 12: Chapter 2

12

Character

Char type is used to represent characters such as letters, digits, or special symbols like '?'. To allot a character to a variable, we need to put these characters in single quotes ie ''. For example 'A', 'z', '@'.

Char Data Type Byte Ranges

Char 1 -128 .. 127 Unsigned char 1 0 .. 255

Strings In generally string refer the character which include in the symbol “ “. For example “ “ “Hello, how are you?” If there are no character within that symbol it will known as null string. If a string is "Hello! ". Then the string will be stored in memory in the following circumstances:

H e l l o ! „\0‟

2.3.3 Identify the operators used in programming.

Refer back 2.1.2

2.3.4 Explain the operators used in programming. a. Mathematical operators

Refer back 2.1.2

b. Relational operators

Refer back 2.1.2

c. Logical operators

Refer back 2.1.2

Page 13: Chapter 2

13

2.3.6 Explain the differences between a formula (equation) and an expression.

Equation Expression

An equation is a SENTENCE.

One solves an equation. An equation HAS a relation

symbol.

Ex.

1. Ten is five less than a number. 10 = x - 5

2. A number is less than five.

x < 5

An expression is a PHRASE, a sentence fragment.

One simplifies an expression.

An expression HAS

NO relation symbol.

Ex.

3. a number less than five x

4. five less than a number

x - 5

2.3.7 Convert formula into expression and vice versa.

Special Expression Basic Expression (Formula)

i + = j; i = i + j;

i - = j; i = i – j; i * = j; i = i * j;

i / = j; i = i / j;

i % = j; i = i % j;

Page 14: Chapter 2

14

2.4 Understand Array And Programme Design

2.4.1 Define what an array is.

Array The C language provides a capability that enables the user to define a set of ordered data items known as an array. Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number. In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a number called as index number or subscript. Array by definition is a variable that hold multiple elements which has the same data type.

Declaring Arrays

We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax:

data_type array_name[size];

For example, to declare an integer array which contains 100 elements we can do as follows:

int a[100];

There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].

Initializing Arrays It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array.

int list[5] = {2,1,3,7,8};

Page 15: Chapter 2

15

2.4.2 Describe array structure.

m Score [0]

m + 4 Score [2]

m + 6 Score [3]

m + 8 Score [4]

m + 10 Score [5]

m + 12 Score [6]

m + 14 Score [7]

m + 16 Score [8]

m + 18 Score [9]

Memory

Refer to the diagram above, m represents the address of the first element in the array. As the value of an integer array element, then the space used by each element is 2 bytes.

2.4.3 Identify single-dimensional array and multi-dimensional array.

Single –dimensional array Example

#include <stdio.h>

void main()

{

const int size = 5;

int list[size] = {2,1,3,7,8};

int* plist = list;

// print memory address of array elements

for(int i = 0; i < size;i++)

{

Page 16: Chapter 2

16

printf("list[%d] is in %d\n",i,&list[i]);

}

// accessing array elements using pointer

for(i = 0; i < size;i++)

{

printf("list[%d] = %d\n",i,*plist);

/* increase memory address of pointer so it go to the next

element of the array */

plist++;

}

}

Here is the output list[0] is in 1310568

list[1] is in 1310572

list[2] is in 1310576

list[3] is in 1310580

list[4] is in 1310584

list[0] = 2

list[1] = 1

list[2] = 3

list[3] = 7

list[4] = 8

You can store pointers in an array and in this case we have an array of pointers. This code snippet use an array to store integer pointer.

int *ap[10];

Multi – dimensional array

Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row &

Page 17: Chapter 2

17

the other the column. The declaration of two dimension arrays is as follows:

data_type array_name[row_size][column_size]; int m[10][20]

Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]

Elements of multi dimension arrays:

A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.

marks [0][0]

35.5

Marks [0][1]

40.5

Marks [0][2]

45.5

marks [1][0]

50.5

Marks [1][1]

55.5

Marks [1][2]

60.5

marks [2][0]

Marks [2][1]

Marks [2][2]

marks [3][0]

Marks [3][1]

Marks [3][2]

Initialization of multidimensional arrays:

Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces

Page 18: Chapter 2

18

Example:

int table[2][3]={0,0,0,1,1,1};

Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as

int table[2][3]={{0,0,0},{1,1,1}}