Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
3 Language
3.0. Introduction
In Units 1 and 2, you were exposed to an overview of the basics of program
development. Let’s continue exploring programming language in more detail.
Writing programs in machine language is not an easy task for the programmer.
To overcome this problem, many different programming languages have been
created to enable instructions to be given in forms other than machine language.
These instructions need to be translated into machine language before they can be
run by a computer. This Unit will give an explanation on the different types of
programming languages. Next, C language and its environment will be
introduced. At the end of this Unit, one example of a simple C program will be
discussed.
3.1. Objectives
Every computer has its own machine language that is its native language.
Programs written in machine language is normally stated in binary numbering
system (0 and 1) or in the hexadecimal numbering system. Every machine
language instruction will state the operation that is to be executed and the
memory cell that is involved for that operation.
Do you know the other factors why writing programs with machine language
and assembly language did not continue? Programs written in machine language
or assembly language are machine-dependent. Assuming we write a program in
assembly language for a particular computer and want to run this program on
TOPIC 3 PROGRAMMING LANGUAGE W 46
another type of computer; it has to be written again in assembly language for that
computer. A language that is machine-independent is needed to make it easier
for programs to be transferred from one computer to another. Many high level
languages have been created for this reason. Using a high-level language, a
programmer would be able to write programs that are simple and clear. For
example, the following statement is written in C language (which is one of the
high-level languages) to code the example equivalent to the one given earlier to
calculate the sales amount.
High-Level
Explanation
Languages
C A universal language that is usually used to write system
software or system applications.
C++ Extention from C that provides support for object-oriented
programming.
Ada Language that is developed for the Defence Department in
the United States for its real-time systems.
Lisp For artificial intelligence applications.
Pascal For teaching programming.
Fortran For scientific and engineering applications.
COBOL For processing business data.
TOPIC 3 PROGRAMMING LANGUAGE W 47
ACTIVITY 3.2
3.1
3.3. LANGUAGE
Let’s look into the past to see the history of C Language in short.
The C language history has links with the existence of B and BCPL programming
languages. BCPL is a language that is used to write operating systems and
compilers developed by Martin Richards in the year 1967. In the 1970s, Ken
Thompson developed the B language that is used in developing the UNIX
operating system at Bell Laboratories. Based on B language, Dennis Ritchie
developed the C language at Bell Laboratories in 1972. This language was then
used to develop UNIX.
For more information on the history of C programming, visit the web site
http://syazwan.tripod.com/introc.htm or any other relevant sites.
Figure 3.1 on the next page shows a C development environment. It shows six
phases that are involved in the process of developing a C program that can be
executed that is:
• editing,
• pre-processing,
• compiling,
• linking,
• loading and
• executing.
Activity 3.3
Identify software that you can use to edit and compile programs.
TOPIC 3 PROGRAMMING LANGUAGE W 50
Program 3.1
#include <stdio.h>
B
void main(void) {
printf(“Welcome to AU!\n”); C
}
This section will explain one easy C program example (see Program 3.1). This
program will display the following output when executed:
Welcome to AU
Notice however that the file name stdio.h in the pre-processor statement is
surrounded by the symbol < and >. This is actually to let the pre-processor know
that the file is found in the usual place. This usual place is dependent on the
computer’s environment. For example, in the UNIX environment, the normal place is
stated in the file .profile. Whereas in the DOS mode, it is normally stated in the
file autoexec.bat.
TOPIC 3 PROGRAMMING LANGUAGE W 51
The code that is marked as C in Program 3.1 is a function definition. The function
that is defined in the program is called main() function. The main() function is a
special function that is the starting point in the execution of any C program.
Notice that the function definition is made up of two parts. The first part is the
function head that provides specific information on the function that is defined;
for example, function name. The second part is the function body which is
statements enclosed in { and }. When a function is called, the statements within
the body will get executed. In the case of main() function in the program 3.1,
the body only contains one statement which is:
printf(“Welcome to AU!\n”);
This statement is the calling of the function printf() which is one of the
functions that is available in the C standard library functions. We can call this
function printf() if we need to output a string on the computer screen. In the
statement above, the string “Welcome to Unitem!\n” is passed to the
printf() function to be output.
The function will display every character in the string except the enclosing
double quotes (which is the character „) and the control character \n at the end of
the string. The double quotes are the markers for the start and end of the string.
The control character \n is called the new line character. When this character is
found in the printf(), function, it will move the cursor to the beginning of the
next line. The new line character is one of the many control characters in the
printf() function. Every control character will have a specific meaning in the
functions given.
ACTIVITY 3.4
In Unit 3.4, there were symbols which were used in program 3.1. Can you
explain them briefly?
Symbols Explanation
/*.........*/
#include
{.........}
“\n”
TOPIC 3 PROGRAMMING LANGUAGE W 52
Activity 3.5
1. Write/edit program 3.1 using notepad and save the file with the
name atur.c.
WELL
WELCOME
WELCOME TO
WELCOME TO AU
7. What does the following do in programming?
Unit 4 Variables
4.0. Introduction
Before you read this Unit further, how about interpreting the phase below:
Now, let us pay full attention to this Unit. When a composer composes a new
song, he/she will give a title to the song. Your parents spent some time choosing a
name for you. Similarly, when we write a program we need to choose an
appropriate name for the file, variables, constants, functions and the rest. This
name is the identifier. The identifier is the official word used for any name in a
high-level programming language. In this Unit, we will go into detail about
variables and how to name them.
4.1. Objectives
Next, let us see how each of the characteristics above is applied in a program.
Variables are named as an identifier that is declared by the user. This name has
to be:
• appropriate,
• easy to understand and
• gives a clear meaning towards the value that it represents.
This name is used to name a memory area that will be used to keep the value of
the variable.
There is a guideline in choosing a name for a variable in the C language which is:
1. Variable name can only contain letters, digits and underscores ‘_’.
2. Variable names cannot start with a digit (number).
3. Reserved words in C cannot be used as variable names.
Next, there are some examples of variable names that are valid.
We can give variable names up to 31 characters. The 32nd character onwards will
not be taken into consideration (except global variable names that would not be
discussed in this text).
System identifiers usually start with the character ‘_’. There, we are not encouraged
to use the character ‘_’ as the beginning for identifiers (like _total) to avoid
confusion. Both lower case and capital letters can be used to name variables.
However, the C is case sensitive, where lower case letters are considered
different from capital letters. Observe that each of the variable names below is
different in C.
The best way to name a variable is with a name that represents the value that is
kept in the identifier. Therefore, sometimes a variable name can be made up of
two words or more. We cannot separate the words with spaces. This is because it
is against the first rule in naming identifiers. Identifiers that have a space in
between are not valid.
For identifiers that have two or more words, we can join them with a ‘_’
character (like big_total). Nevertheless, the usual practice is to write it as:
• Start with the first word being a lower case letter
• Start the second word with an upper case letter.
Reserved words are words that have special meanings in C and cannot be used
for other reasons. All reserved words come in lower case letters.
Just like reserved words, standard identifiers also have special meanings in C. In
the sample programs that you have seen before, standard identifier printf is an
operational name that is declared in the stdio.h library. Standard identifiers
can be re-declared and used by the programmer for other reasons which is not so
for reserved words. However, after re-declaring for another reason, the standard
identifier cannot be used for its original use.
ACTIVITY 4.1
So far, you have been introduced to variables, reserved words and standard
identifiers. Can you think of the differences among them?
The following identifiers are not valid. State why each of them is not valid.
Identifier Reason
(a) 2001SeaGames
(b) SEA GAMES
(c) %passes
(d) width+height
(e) double
TOPIC 4 VARIABLES W 57
XERCISE 4.1
Variables can represent different types of data. Data types that are used will
determine the variable type. Consider Table 4.1 below. These data types are usually
used in C programs.
Declaration Type
char Character
int Integer
float Real numbers
double Real numbers with high precision
When a variable has a certain data type, it means that the variable can only
represent data of that type. For example, a variable of type integer, C assumes
that only whole numbers can be used to represent those values.
There are also extended data types that use a qualifier. Unsigned, signed,
short, long, unsigned short, signed short, unsigned long and
signed long are qualifiers that exist in C.
Variables can be used to keep input data and the calculation results or logic
manipulations. Values that are kept by variables can change throughout program
execution.
The declaration of a variable is as follows.
Syntax:
data_type variable_name;
Different variables are used to keep different types of data. Therefore, in the
variable declaration, it has to be mentioned what data type the variable will
contain. In the example above, identifier marks1, marks2, marks3 and
marks4 are declared as type int, identifier averageMarks is of type double
and identifier grade is of type char. Notice in the example above, a few variables
of the same type can be declared in a group by separating the names of variables
with a comma.
Cell sizes will be discussed in the next Unit. However, storage classes will not be
taught in this course.
Activity 4.2
State whether the variables given are valid or invalid.
variable = value;
? ? ?
? ? ?
10 25 250
Activity 4.3
1. Given a program code segment below, what is the value of the
variable marks after all the statements have been executed?
int marks;
marks = 10;
marks = 20;
marks = 30;
3. State whether the variables below are valid. If not valid, state
the reason.
4.6. SUMMARY
ES
5.0. Introduction
We have seen two types of input and output data. One is of character type, for
example, your name and another that is of the numeric type for example, your age.
Data of character type. is represented by char data type. Numeric data is
represented by data types int, float or double.
5.1. Objectives
By the end of this Unit, you should be able to:
state the cell size and range for a particular data
differentiate 3 types of data
choose the type of data that is suitable for the variable depending on the
type of value to be represented.
Bytes is the unit for cell sizes. Variables are assigned cell sizes or memory spaces
that are different according to their data type. Variables of int type are given a
cell size of 2 bytes that can keep numbers up to a maximum of 32767 that is a range
of -32 768 to 32 767
Variables of float type are also assigned memory cell size of 4 bytes and can
TOPIC 5 DATA TYPES W 63
Let us see an example of initialising variables and memory cell sizes assigned for
each declaration in Table 5.1 below.
The size of the memory cell can double by using the qualifier long in a variable.
See the example above.
Char data type is used to represent characters like letters, digits, or special
symbols like ‘?’.
A character can be read, printed and changed to an integer value. We can also do
character value comparisons by using operators like equal (==) or not equal (!=),
and relational operators like <, <=, > and >=. To understand how character
values can be compared, we need to know how each character is represented in a
computer. Each character has its own numeric code that is unique, using the
ASCII Codes (American Standard Code for Information Interchange).
If you want to know more about ASCII codes, visit websites that are relevant. Binary
TOPIC 5 DATA TYPES W 63
representation of this code is kept in the memory cell and the values can be known.
The binary numbers can be compared by using relational operators just like
comparing normal numbers. Character code usually used is ASCII code.
Character value range that can be represented by char type is between -128 to 128.
TOPIC 5 DATA TYPES W 64
ANSI C (American National Standards Institute) describes three types of data types
that can be used for manipulating real data types:
1. float
2. double
3. long double
All types above can keep real values like 0.001, 2.0 and 3.14159. Choice
is made depending on which range of real values are to be represented. Table 5.2
below shows the range and number of bytes that are needed for each of the real
type numbers.
ACTIVITY 5.1
1. There are three types of basic data types that can be stated till now,
which are: int, char and float. char can
contain letters, digits and symbols. Why do we still need int and
float when char can contain all types of characters? Give your
opinion.
4. State the data type that is suitable for each of the values below so
that memory space wastage does not happen:
5.1
5.6. SUMMARY
• Cell sizes that are allocated for one variable is dependent on the data type
declared for it.
• Before determining the data type that is suitable, you have to observe all the
possible values that can be taken by a variable.
EARNING OUTCOME
6.0. Introduction
Constants are fixed values that cannot change throughout the execution of the
program. Constants can be categorised into many types following its data type,
which is integer constant, real constant, character constant or string constant.
This Unit will help you identify each constant more clearly.
6.1. Objectives
Integer constant refers to a value (integer number) that is fixed. There are a few
types of integer constants. It is divided by the number system that is used like
decimal, octal or hexadecimal systems.
Example:
Decimal :0 2 99
Octal :0 07 074
Hexadecimal : 0X 0X1 0X7A
Activity 6.1
Real constants take their value just like real values in the number system. Float
dot notation or exponent notation, or both can represent real constants. A suffix
is added to the floating-point constant to specifically state the type. The floating-
point constant that does not have a suffix is categorised as type double. See the
examples in Table 6.1.
Exponent notation for real constants can be written as 1.234567e5. This is the
same as the scientific notation 1.234567 x 105. The value is the same in this equation:
333 . 77777 e - 22
If floating point exists, the integer part, or divisor or both, must exist. If there is
no floating point, both the integer part and exponent must exist. Both ‘e’ or
‘E’ can be accepted as a sign of an exponent. Here are some examples of valid
floating-point constants. For example:
3.14159
-3.14159 (negative value)
314.159e-2F (float type)
0e0 (same value as 0.0)
1. (same value as 1.0, but more difficult to read)
Activity 6.2
Any strings (including spaces) in between double quotes are a character array.
Arrays that have only numerical digits are not a number but are numeric digit
arrays where no arithmetic operation can be done on it.
Double quotes only surround the array. They are not part of the array. Each string
constant will have a null character (written as ‘\0’) automatically by the C compiler
as an end of the character array. An example of the array “ZOU” is actually “ZOU
\0”. The length of a character array is the number of characters in the array plus a
null character. Therefore, the length of the character array “ZOU” is 4.
Because the character array has an end character, therefore a character array for a
character is not the same as a character constant. For example, the character array
“A” is not the same as the character constant ‘A’ because “A” is the combination
of a character constant ‘A’ and ‘\0’.
TOPIC 6 CONSTANTS W 72
Activity 6.3
2. Which one of the answers below is a valid integer, double, float, char
or string constant? For every valid constant, state the data type.
(a) 15 (d) .123F
(b) ‘XYZ’ (e) ‘x’
(c) ‘*’ (f) “X”
TOPIC 6 CONSTANTS W 73
6.6. Summary
• Constants include many types of constants such as integer and fixed point
constants, character constants such as ‘A’ and character array constants such
as “ABC”.
• Character constant and character array (string) constant are different.
• Integer constant refers to a value (integer number) that is fixed.
• Real constants take their value just like real values in the number system.
Float dot notation or exponent notation, or both can represent real constants.
• The character constant is quite unique because it must be surrounded by
single quotes.
• String constants are made up of some characters surrounded by double
quotes.
TOPIC 6 CONSTANTS W 74
TOPIC 7 INPUT AND OUTPUT W 75
7.1. Objectives
printf(output_format [, value_list]);
TOPIC 7 INPUT AND OUTPUT W 75
output_format: an array that will determine the form of the output depending
on the value list.
value_list: can be made up of variables, constants, statements or
combinations.
Data that is easiest to print or output is a string. We just need to write the string
that needs to be printed as the output_format in the printf()function. The
string will print as we have written it. As an example:
Notice that all the characters in the double quotes „ “ are printed including the
spaces.
printf() function does not execute a new line command automatically. This
means that the cursor placed on the screen will be at the end of the last character
of the sentence printed.
The next printf() statement will be printed starting from the cursor
placement earlier. Therefore, an escape sequence ‘\n’ is put at the end of the
statement if the cursor is to be on a new line.
Other than the escape sequence ‘\n’ there are other characters that can be used in
the string output_formats as given in Table 7.1.
TOPIC 7 INPUT AND OUTPUT W 76
Activity 7.1
Specification Meaning
%s Output a string
%c Output a character
%d Output an integer
%f Output float/double
%e Output float/double using scientific notation
(a) %s specification
Assume name is a string variable that can be assigned the value Najwa
Mawaddah. Consider how the specification %s interprets the variable to
output in Program 7.1.
Program 7.1
/* Prints name */
#include <stdio.h>
void main() {
char name[] = “Peter Moyo”;
printf(“%s”, name);
Do know what will the output be? Yes, the output will be:
Peter Moyo
(b) %c specification
Now, let’s look at the %c specification. Do you know the use of this
specification? This specification will be compared to the character value that
will be printed. Study Figure 7.1 to understand this concept.
character1 = ‘U’;
character2 = ‘N’;
character3 = ‘I’;
character4 = ‘T’;
character5 = ‘E’;
character6 = ‘M’;
printf(“%c %c %c %c %c %c “,character1,
character2, character3, character4,
character5, character6);
Program 7.2
At the second printf() function call, the statement value1 – value2 will be
evaluated first and the result is 4.45. This value will fit the %f specification in
the string given. Because the float data type has a precision of 6, therefore the
output obtained is in precision of 6 decimal spaces. The output displayed is as
follows:
First value = 10
Second value = 4.450000
Output specification can be combined into one printf() statement. See relevant web
sites on how this can be done.
TOPIC 7 INPUT AND OUTPUT W 80
Activity 7.2
void main () {
char name[] = “Peter Moyo”;
int age = 20;
float height = 1.53;
(a) printf(“*\t***\t*****\n”);
(b) printf(“*\b***\n*****\n”);
(c) printf(“*\r***\n*****\n”);
TOPIC 7 INPUT AND OUTPUT W 81
ACTIVITY 7.3
In this section, we will see how to receive input with the scanf() function. This
function allows us to interact with the written program. Input is from the
keyboard.
What happens here is that the value that is input will be matched to the variable
based on the formats given. Next, the value represented by the variable will be
used in the program and usually produces output. Let’s take a look at the general
form for scanf()function:
scanf(input_format [, variable_list]);
For basic variable (integer, real and character) input, we need to list the address
location for the variables. The address location stated here uses the & operator for
list variables. The following statement:
scanf(“%c%d”, &character, &num);
will read two inputs. Assume character and numare variables of type char and
int respectively. The first input is a character value that will be kept in the
memory location called character. The second input is an integer value that is
kept in the memory location for variable num.
Program 7.3
/* Program to modify date format */
#include <stdio.h>
void main () {
int day, month, year;
scanf(“%d %d %d”, &day, &month, &year);
printf(“Day: %d, Month: %d, Year: %d”, day,
month, year);
}
Observe program 7.3 above. When the program is executed, it will wait for us to
enter a value for day, month and year.
11 9 2001
One main problem in the program above is that the programmer assumes that
the user of the program knows what the values to be entered are. Normally,
when writing programs, we will display a suitable message to inform the user of
the type of values to enter.
TOPIC 7 INPUT AND OUTPUT W 83
Activity 7.4
1. Write, compile and execute the program which will input 3 name
initials and age.
7.4. Summary
EARNING OUTCOMES
8.0. Introduction
When you studied mathematics in secondary school, you saw symbols like +, -, x,
<, > etc. These symbols are used to manipulate data. These symbols are known as
operators. Before we write programs that are more complex, it would be good to
remember some symbols to manipulate the data. In C language, there are many
types of operators. There are arithmetic operators, relational operators, logic
operators, increment and decrement operators cast operator and conditional
operator. This chapter will explain in detail about these operators.
8.1. Objectives
By the end of this Unit, you should be able to:
write appropriate statements using 5 types of operators
write arithmetic expressions using C syntax
evaluate and write expressions to be used in single, double or
compound assignment statements
Most of the symbols above behave in the same way as normal arithmetic operators.
Addition, Minus, Multiply and a few cases of Division operator would give the
same result as normal arithmetic operators.
Therefore, the addition, minus and multiply operators will not be discussed in
detail. Please recall the basic concepts of addition, subtraction and multiplication
from your mathematics subject.
Please note that the symbol used in the multiplication operation is * and not x. The
Operation Result
5 / 2.5 2.0
5.5 / 2.0 2.75
5.0 / 10 0.5
Observe Table 8.3 above. In the first example, immediately we get the division value
to be 2. Because the division is a real division (one of the operands is a real number),
therefore the result of the division has to be written as a real number 2.0.
Activity 8.1
Which one of the answers given below would keep the value of
result?
A) 3 C) 3.7
B) 3.0 D) 3.75
Modulus operation would have the result of the remainder of the integer division.
The symbol used for this operation is %. Both the operands in this operation must
be integer operands.
Activity 8.2
5 + 6
14 * 5 * 2
21 - 6 + 7 * 4 / 2
7.5 * (2.0 - 4.52)
Precedence Operation
High *, /, %
Low +, -
3 + 10/3
3 + 3
Operator / has a higher precedence level, therefore it is evaluated first. The result
from 10/3 division would be the operand for the addition operation and the
result is 6.
ACTIVITY 8.3
If you do not want the arithmetic expression evaluated using the precedence levels,
we need to write the expression using brackets. Expressions in the brackets
would be evaluated first.
To ensure the operator with a lower precedence is executed first, the solution is to
use brackets (). For example:
(12 - 6) * 4
= 6*4
= 24
ACTIVITY 8.4
What about the case below? Can you show the steps?
(9 - (3 + 2)) * 3
7
15 + 5 +
2
Activity 8.5
variable = expression;
Program 8.1
/* Calculate body weight index */
#include <stdio.h>
void main() {
float weight, height, bodyweightIndex;
Activity 8.6
Using your computer,
1. Write, compile and execute Program 8.1.
2. Change Program 8.1 by allowing the use to input the weight and
height values.
a = b = c = 40;
Observe the example above. Remember that any assignment statement will solve
the expression on the right and assign the value of the expression to the variable on
the left. Look at how the statements are worked out:
TOPIC 8 OPERATORS AND EXPRESSIONS W 93
Multiple statements are useful when we want to give initial values to some
variables that are newly declared, that is before they are used. Using the multiple
expression statements, we do not have to write one assignment statement for every
variable. This will reduce the lines of the program code.
The example below shows the variable age and numOfSiblings assigned the
initial value of 0 in one multiple expression. The same would be for the variable
weight and height assigned initial value of 0.0 in one multiple expression.
Activity 8.7
A) 10.000000 C) 20.000000
B) 20 D) none of the above
TOPIC 8 OPERATORS AND EXPRESSIONS W 94
where the variable’s original value is added to or multiplied by another value and
is assigned back to the original variable. It is normally written as:
If the value of weight originally is 45, the expression on the right (weight + 1.5)
will result in the value 46.5 (see (1) in Diagram 8.1). This value is assigned to the
variable weight (see (2)). It means that the original weight (45) will be replaced
with the new value which is 46.5 (see state after (2)).
In C, statements like this can be written using compound operators. Table 8.7
below shows compound operators.
Precedence level for the compound operators is the lowest. This means that this
operator will be evaluated last of all while solving some expressions. Observe the
statement below:
Based on the precedence level, the statement above is solved in this manner:
Activity 8.8
Assume that x has the value of 1 0 . 0 . What is the value that is assigned to
x after the statement below is executed?
x = x - 20.0;
A) -10 C) -20
B) -10.0 D) 10
The task of these operators is to compare the values of two expressions; either equal
to, not equal to, less than, more than etc. Table 8.8 below lists the relational operator
symbols and their meanings.
TOPIC 8 OPERATORS AND EXPRESSIONS W 96
Activity 8.9
Assume that x has the value of 15.0 and y has the value 25.0. What is
the value for these relational expressions?
Expression Value
x! = y
x >= y - x
x<x
x == y = x - y
Relational operators can only test one case at a time. If we want to test a few cases
that are related to get a result, we can use the logical operator. Table 8.9 below
lists the logical operators.
Symbol Meaning
&& and
|| or
! not
TOPIC 8 OPERATORS AND EXPRESSIONS W 97
Operator && and ⎢ ⎥ must have two operands whereas the operator ! has only
one operand. Table 8.10 below shows how the logical operator functions. The
table is known as the truth table. 1 represents truth and 0 represents false.
Table 8.10: Logical Operator Examples
a b a && b a⎢⎢b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
a !a
0 1
1 0
(c) ! (c > a)
<=> ! 1
<=> 0
Activity 8.10
Expression Result
a) c = = a + b ⎥ ⎥ ! valid
b) a! = 7 && valid ⎥ ⎥ c >= 6
Increment and Decrement operators are unique operators. Table 8.11 below
shows the operators.
Symbol Meaning
++ Add 1 to the operand
-- Subtract 1 from the operand
This operator needs one operand only. That operand is usually an integer
variable. Do you still remember integer variables? If you do not, please refer to
Chapter 5. It can also be written in the form of an assignment statement. Table
8.12 below explains the meaning of increment, decrement, and the statements
that are equivalent to them.
TOPIC 8 OPERATORS AND EXPRESSIONS W 99
To increase or decrease the value of one variable, the position of the operator
does not matter, whether it is a prefix or postfix of the variable. However, when
the operator is combined to other operators in an expression, the position would
determine the value returned. Look at table 8.13 below:
Expression Meaning
i++ Value i increased after used in expression
++i Value i increased before used in expression
i-- Value i decreased after used in expression
--i Value i decreased before used in expression
Also consider when we use the operator ++i (prefix increment) as shown below:
i = 5;
j = ++i - 2;
i = 5;
i++;
j = i - 2;
TOPIC 8 OPERATORS AND EXPRESSIONS W 100
Activity 8.11
1. What is printed?
i = 3;
printf(“%d\n”, i);
printf(“%d\n”, --i);
printf(“%d\n”, ++i);
2. Write the output for the two sets of sub programs below:
Sub program Output
Postfix decrement
i = 7;
printf(“%d\n,i);
printf(%d\n”,i--);
printf(%d\n,i);
Prefix decrement
i = 7;
printf(“%d\n,i);
printf(%d\n”,--i);
printf(%d\n,i);
3. If
Expression j Value
i = 5
j = ++i –2;
Therefore j = ?
i = 5, j = 3;
i++;
j = i – j
Therefore j = ?
average value and possibly that the average value is of real type. Therefore, we
will declare the variable average as float type.
obtained is 5.0. But when the value of total = 15 and count = 2, average
value obtained is 7.0! In this case, both the operands for the divide operation are
of type integer. So, integer division is carried out and would result in integer value.
Even though this integer value is assigned to a real value, the decimal part is
truncated.
In cases like this, we need to do a real division operation. The easiest way to do this
is by changing the value of total variable and/or count to type float before
the division operation is done using the cast operator.
Take note here! We do not redefine total and count as type float because
we want to retain the value as an integer for the other parts of the program. The
changes made are as follows:
The changes are made only at the part where they are needed. Cast operator would
change the value of total and count temporarily to a real value. Therefore,
the division that is executed will be real division and will result in a real value too.
TOPIC 8 OPERATORS AND EXPRESSIONS W 102
Activity 8.12
Generally, to get a value for the conditional expression above, we first need to
determine whether expression_1 is true or false. If expression_1 is true
then, the value of the conditional operator is expression_2, but if
expression_1 is false, the value of the conditional operator is expression_3.
m ? mx + c : c;
y = m ? mx + c : c;
if (m)
y = mx + c;
else
y = c;
Activity 8.13
What is printed?
2. For each of the algebra expressions below, write the equivalent C
arithmetic expression.
a) b2 - 4ac b) a (b+c)
Expression Value
a) k = j ++;
b) k = i * j-;
c) k = ++ j;
d) k = i * -j;
TOPIC 8 OPERATORS AND EXPRESSIONS W 104
8.10. Summary