Sei sulla pagina 1di 67

Programming

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.

To command a computer to do a task, the instruction that is given must be


written in the computer’s native language which is machine language. You might
not have heard the word machine language but continue reading and it will be
explanation and discussed later.

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

By the end of this Unit, you should be able to:


 differentiate the three different types of programming languages by
levels
 explain a little on the history of C language development
 describe the six phases that are involved in developing a program in C
3.2. Programming language types

Programmers write programs using programming languages. There are many


categories of programming languages. Programming languages that are most
popular and normally used are high-level languages. In this Unit, we will see
different types of languages that are machine language, assembly language, and
high-level language.

3.2.1 Machine language

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.

3.2.2 Assembly Language

The second level language is assembly language. Programming in machine


language was felt to be too difficult and slow. To make programming easier,
mnemonic language that resembles the English language is created and used to
represent operations in machine language. This is the basis of assembly language.
To run a program in assembly language, a program called the assembler is used
to interpret the program to machine language.

3.2.3 High level language

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.

amount = itemPrice + salesTax;

Compared to assembly language, the high-level language resembles the natural


language more and with that it is easier to read and understand.

Just like assembly language, a program in high-level language needs to be


compiled into machine language before it can be executed. The process of
compilation is accomplished by the compiler program. Some high-level
languages and their uses are listed in Table 3.1 below.

Ta ble 3.1: High-level Languages

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

 Before we continue reading the next Unit, create a networked


mind map of the three levels of programming languages that you
have just read. Present that in your tutorial.
 Give two advantages of writing programs in C language compared
to machine language.

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.

The C program development can be done on many computers as C language


does not depend on the machine or hardware. Through this portability feature,
programs that are written in C language would be able to be transferred to any
computer with minimal changes. Other than using important concepts in BCPL
and B, many different features like pointers are added into C to make it a strong
language. The other advantage of C is the wide usage and its high ability.

Due to the existence of many variations of C language, the American National


Standards Institute (ANSI) has created a standard C which is called ANSI C. This
standard enables us to write C programs that are portable.

For more information on the history of C programming, visit the web site
http://syazwan.tripod.com/introc.htm or any other relevant sites.

3.4. C programming environment

Generally, the C programming system is composed of its environment, its


language and standard library:
TOPIC 3 PROGRAMMING LANGUAGE W 48

1. Environment : is related to the process it goes through to develop a


C program that can be executed.

2. Language : refers to the aspect of syntax or the representation of


algorithms in C language.

3. C standard Library : makes available the supporting functions that can be


reused in program development. Among functions
that are available in the standard library are
mathematical functions like sin( ) and sqrt( ),
functions to do input and output, graphical
functions and others.

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.

Further explanation on each phase will give a focus on the development of


programs in the MS-DOS environment. For Windows operating system, the
environment can be created through the MS-DOS prompt icon.
TOPIC 3 PROGRAMMING LANGUAGE W 49

Figure 3.1: C Development Environment

Activity 3.3

Identify software that you can use to edit and compile programs.
TOPIC 3 PROGRAMMING LANGUAGE W 50

3.5. Sample c program

Program 3.1

/* This program will print a greeting


Welcome to AU */ A

#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

The statement that is marked as A in Program 3.1 is a comment to explain the


program’s meaning. Comments are any text that is surrounded by the symbols /*
and */. Comments are inserted to give information or explanation on the
program code. A program can contain as many comments as needed and can be
put anywhere in the program code. The comments are not compulsory in a
program, but we are encouraged to put in comments so that programs are easily
read and understood.

Statements that are marked as B in Program 3.1 are said to be pre-processor


statements. Pre-processor statements are easily known because they start with the
symbol #. Here, pre-processor statements used are the #include statement.
When executed, the pre-processor will insert a copy of header file called
stdio.h into the program code at the given statement line. This statement is
needed in Program 3.1 because the header file has the function declaration
printf(). We will see later how the program will use the function to output
something.

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.

2. Compile the program

3. Execute the program

4. Compare the output.

5. Edit the program by changing the statement


printf(“Africa University”);

6. Edit the program 3.1 so that the output below is displayed:

WELL
WELCOME
WELCOME TO
WELCOME TO AU
7. What does the following do in programming?

Assembly Language C Standard Library


Compiler Editor Environment
Linker Loader Machine Language
TOPIC 3 PROGRAMMING LANGUAGE W 53
3.6. Summary

• The machine language is the computer’s natural language. Programming in


machine language is in the binary format.
• Assembly language is a mnemonic language and is closer to the English
language to do operations and operands.
• High-level language is closer to natural language.
• A program written in assembly language or high-level language has to be
translated into machine language before it can be executed.
• C Language is a high-level language.
• In the C environment, a program has to go through the following phases in
its development process that is editing, pre-processing, compiling, linking,
loading and executing.
TOPIC 3 PROGRAMMING LANGUAGE W 54
TOPIC 4 VARIABLES W 55

Unit 4 Variables

4.0. Introduction
Before you read this Unit further, how about interpreting the phase below:

“The best remedy is being diligent”


-Imam Ghazali

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

By the end of this Unit, you should be able to:


 distinguish between variables, reserved words and standard identifiers
 differentiate between variables that are valid and invalid
 write syntax to declare and initialise variables.

4.2. Variable naming


TOPIC 4 VARIABLES W 55

Variables are an example of an identifier. It is used in certain program blocks. It is


initialised before it can be used. To declare a variable, we need to associate a name
and the data type to represent a particular value.

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.

4.2.1 Rules to name a 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.

tot3 big_Total _total BigTotal big_total

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.

total ≠ Total ≠ toTAL ≠ TOtal ≠ toTal


TOPIC 4 VARIABLES W 56

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.

Therefore, the identifier above is better written as bigTotal.

4.2.2 C reserved words and standard identifiers

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

4.3. Variable types

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.

Table 4.1: Basic Variable Types

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.

4.4. Variable declarations

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;

Next are some examples of variable declarations:

Table 4.2: Variables Declaration

Data Types Variable Names


int marks1, marks2, marks3, marks4;
double averageMarks;
char grade;
TOPIC 4 VARIABLES W 58

When declaring variables, the compiler will be notified of four items:


1. Variable name
2. Variable type
3. Size of cell of variable in the memory
4. Variable storage class

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 VALID or INVALID


(a) Address2
(b) 33road
(c) _empty

4.5. Variable assignment


TOPIC 4 VARIABLES W 59
We can assign values to a variable by using the following statement:

variable = value;

Consider the next example:

/* 1 */ int number1, number2, multipliedNumber;


/* 2 */ number1 = 10;
/* 3 */ number2 = 25;
/* 4 */ multipliedNumber = number1 * number2;

When statement /* 1 */ is declared, the memory cell assigned to each


variable is:

? ? ?

number1 number2 multipliedNumber

Statement /* 2 */ assigns 10 to variable number1. and


Statement /* 3 */ assigns 25 to variable number2.

? ? ?

number1 number2 multipliedNumber

Next statement /* 4 */ is executed. When assignment statement


multipliedNumber = number1 * number2; is executed, the right side
of ‘=‘ will be calculated first, that is by doing multiplication on values kept by
variables number1 and number2. The result is 250 and this value will be
assignment to the variable multipliedNumber that is on the left of ‘=‘. Next
is the result of the execution of statement /* 4 */.

10 25 250

number1 number2 multipliedNumber


TOPIC 4 VARIABLES W 60

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;

2. Sketch the memory cell of the program code segment below.

int num, newValue


num = 9;
newValue = num;
newValue = -num;

3. State whether the variables below are valid. If not valid, state
the reason.

(a) tot_Credit_Hours (c) current_bill


(b) _car_tyres_types (d) 8_8_88

4. State which of the identifiers below are (a) C reserved words


(b) standard identifier, (c) other valid identifier and (d) invalid
identifier.

(a) void (d) printf


(b) MAXIMUM_BIL (e) xyz123
(c) double (f) char
TOPIC 4 VARIABLES W 61

4.6. SUMMARY

• Variables are used to keep data temporarily in memory.


• Variables have characteristics such as name, type and they are used to
represent a value.
• Variables are named as an identifier that is declared by the user.
• Variables can represent different types of data.
• Variables can be used to keep input data and the calculation results or logic
manipulations.
TOPIC 5 DATA TYPES W 63

Unit 5 Data Types

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.

5.2. Cell sizes and qualifiers

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

keep larger numbers up to 1038.

Let us see an example of initialising variables and memory cell sizes assigned for
each declaration in Table 5.1 below.

Table 5.1: Relationship Declaration, Variables and Total bytes

Declaration Memory Total Bytes


int age; age 2 bytes
float height; height 4 bytes
long int multiples; multiples 4 bytes

The size of the memory cell can double by using the qualifier long in a variable.
See the example above.

5.3. Integer data type (int)

Intdata type is to represent negative or positive numbers. For example - 77, 0,


999, +999. T h e m emory cell size for inttypes differs according to different
computer systems. In the computers family of 80386 processors and below, the
memory cell size for int is 2 bytes. For processors like SPARC, the cell sizes for
int is 4 bytes.

5.4. Character data (char)

Char data type is used to represent characters like letters, digits, or special
symbols like ‘?’.

To assign a character to a variable, we need to put single quotes as in: ‘ ‘ for


example: ‘A’, ‘z’, ‘3’, ‘?’.

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

5.5. Real data type

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.

Table 5.2: Real Data Type

Real Data Type Number of Bytes Precision Range


float 4 6 10-37 .. 1038
double 8 15 10-307 .. 10308
long double 16 19 10-4931 .. 104932

However, on some computer systems, implementation of double and long double


is the same for the number of bytes allocated.
TOPIC 5 DATA TYPES W 65

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.

2. How many real types are there? List them.


3. Given the declaration below, how many bytes are assigned to
each data type?

Variable Declaration Bytes used


float weight;
double volt1;
char letter;
int hour, minute;
long int second, length;
long double volt2;

4. State the data type that is suitable for each of the values below so
that memory space wastage does not happen:

(a) 0.000067 (d) 123.123456789


(b) # (e) -40000
(c) 30000 (f) 1000000
TOPIC 5 DATA TYPES W 66

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.

• int data type is to represent negative or positive numbers.


• Char data type is used to represent characters like letters, digits, or special
symbols like ‘?’.
• ANSI C (American National Standards Institute) describes three types of data
types that can be used for manipulating real data types: float,double and
long double
TOPIC 5 DATA TYPES W 67
Unit 6 Constants

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

By the end of this Unit, you should be able to:


 identify four types of constants that exist in C language
 differentiate four types of constants by its writing

6.2. INTEGER CONSTANT

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

Change the exponent numbers to decimal numbers.

Exponent Numbers Decimal Numbers


(a) 10300e-2
(b) 1.23456e+6
(c) 123.45e+3

6.3. Real constants

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.

Table 6.1: Real Constants

Suffix Data Type Example


f or F float 3.7F
l or L long double 3.7L

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:

1.234567 x 105 = 1.234567 x 10 x 10 x 10 x 10 x 10


= 1.234567 x 100000
= 123456.7 (floating point has moved to
the right 5 times)

A floating-point constant number can be made up of 4 parts. Let’s see the


example in Figure 6.1:
TOPIC 6 CONSTANTS W 69

Floating point constant like 333.77777e-22.

333 . 77777 e - 22

Integer Floating Point Divisor Exponent

Figure 6.1: Four parts of floating-point constant

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

1. Write the following numbers in scientific notation:

Decimal Numbers Scientific Notation


(a) 1300
(b) 123.45
(c) 0.00426
TOPIC 6 CONSTANTS W 70

2. Give reasons why the real constants below are invalid.

Constant Reasons Why Invalid


(a) 3.14,129
(b) 314159
(c) 2E1.5
(d) 3E 12
(e) .e0

6.4. Character constant

The character constant is quite unique because it must be surrounded by single


quotes. For example:

‘A’ ‘z’ ‘?’ ‘5’

Character constants have certain integer values that is determined by character


code or coding system that is used by a computer. Most computers use ASCII
code representation to represent its characters. For example: character ‘A’ is
valued at 65 in ASCII representation.

Do you know that some characters can be expressed as an escape sequence


character? Well, this sequence starts with the symbol ‘\’ and is followed by at
least one character. The character ‘\’ is an escape character. Therefore, we can
assume the escape sequence character ‘\n’ as meaning, escaped the normal
meaning for n”.

Table 6.2: Escape Sequence Characters for ASCII

Escape Sequence Meaning


'\a' Bell
'\b' backspace
'\f' form feed
'\n' newline
'\r' carriage return
'\t' tab
TOPIC 6 CONSTANTS W 71

'\v' vertical tab


'\\' \
'\'' '
'\”' “
'\055' Octal character value 055
'\xA9' Hexadecimal character value 0xA9
'\0' Null character

6.5. String constant

In C language, string constants are made up of some characters surrounded by


double quotes. Below are some examples of string constants. For example:

“ZOU” “Information Technology” “X”


““ “1, Jln TTS 4/6, TTS” “123”

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

1. For each value below, state if it is a valid constant. If valid, state


the type of constant. If invalid, state the reason.
(a) 1234567 (d) ‘a/n’
(b) \t (e) 0Xabc
(c) “Z\0”

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

Unit 7 Input and Output


7.0. Introduction
We have looked at some output functions in previous Units. These functions
send data to the output device (usually the computer screen) using the formats
that are given. Technically, printf() and scanf() functions are not part of C
language, but is part of the C system. Both these functions exist in the C library
and are kept together with C system. Even though the object code for the functions
are made available by C system, it is your responsibility as a programmer to
declare this function when you want to use it in your program.

ANSI C has introduced a new way to declare embedded functions. It is called


function prototypes. Function prototypes for functions that are embedded in the
C standard library can be found in the header files. Function prototypes for the
functions printf() and scanf() are found in the header file stdio.h. In the
code examples in this Unit, we will see how the header file stdio.h is inserted.

7.1. Objectives

By the end of this Unit, you should be able to:


 use the function printf() to produce output data to the screen using a
particular format
 use the function scanf() to produce input data from the keyboard
using a particular format
 display output according to program segments

7.2. printf() function

As it is translated, the function printf() is sometimes known as a function to


print. We need to remember that printing here means printing to the computer
screen and not to the printer.

printf() function format is:

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.

7.2.1 Printing strings

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:

printf(“Welcome to ZOU class.”);

will produce the output as below on the screen.

Welcome to ZOU class.

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

Table 7.1: Escape Sequence Characters in Output Format

Escape Sequence Meaning


'\a' Bell
'\b' backspace
'\f' form feed
'\n' new line
'\r' carriage return
'\t' tab
'\v' vertical tab
'\\' \
'\'' '
'\”' “
'\055' Octal character value 055
'\xA9' Hexadecimal character value 0xA9
'\0' Null character

Activity 7.1

1. Write a simple program that has the statements below:


printf(“Line 1”);
printf(“Line 2”);

What is the output?

2. Add „\n” to the first statement:


printf(“Line 1\n”);
printf(“Line 2”);

3. Write the output to the segment code below:


printf(“Line 1\n Line 2\n\n”);
printf(“Line 3\n”);
TOPIC 7 INPUT AND OUTPUT W 77

7.2.2 Printing values

If a printf() function call has a list of values to be printed, then the


output_format must use the specifications for those values. Consider the
specification list given in Table 7.2 below:

Table 7.2: Output Specification List

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

Next, we will see how to use the output specification one-by-one.

(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

The variable name will be compared to the specification %s and then


output.
TOPIC 7 INPUT AND OUTPUT W 78

(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.

Figure 7.1: How %c specification works?

Every character constant will be compared with the specification sequence


and output. The value list can also be a list of variables. The same comparison
can be made.

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);

(c) %d and %f specification


When we want to print a numeric value, we have to use the output
specification that is suitable to the type of value. Specification %d is used to
print integer values whereas %f specification is used to print real numbers.
Program 7.2 below shows how to print integer and real numbers.
TOPIC 7 INPUT AND OUTPUT W 79

Program 7.2

/* Printing integer and real values */


#include <stdio.h>
void main() {
int value1;
float value2;
value1 = 10;
value2 = 5.55;

printf(“First value = %d\n”, value1);


printf(“Second value = %f\n”, value1 –
value2);

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

1. Write and compile the computer program below:

/* Program with specification combination output */


#include <stdio.h>

void main () {
char name[] = “Peter Moyo”;
int age = 20;
float height = 1.53;

printf(“%s %s %s\n”, “Name”, “Age”, “Height”);


printf(“%s %s %s\n\n”, “~~~~~~~~~~~~”,
“~~~~~~~~~~”, “~~~~~~~~~~”);
printf(“%s %d %f\n”, name, age, height);
}

2. Replace the printf()statement with the following, and execute


the program:
printf(“%15s %10s %10s\n”, “Name”, “Age”,
“Height”); printf(“%15s %10s
%10s\n\n”, “~~~~~~~~~~~~”,
“~~~~~~~~~~”, “~~~~~~~~~~”);
printf(“%15s %10d %10.2f\n”, name, age, height);

3. Given the declaration statement below:


int count = 5;
float tot = 10.5;
printf(“\n%s%5d\n%s%12f\n\n”, “Calculation:”,
count, “ Total:”, tot);
What is printed?

4. What is the output produced by the following statements?

(a) printf(“*\t***\t*****\n”);
(b) printf(“*\b***\n*****\n”);
(c) printf(“*\r***\n*****\n”);
TOPIC 7 INPUT AND OUTPUT W 81

5. Given the following declaration:


int i;
char c;
Write the output that will be produced by each of the printf()
statements below:
i = 36;
c = 64;
printf(“%d %c\n”, i, c);
printf(“%c %d\n”, i, c);

7.3. The scanf() function

ACTIVITY 7.3

printf() function is frequently used with the scanf()function. Where


are the two function used?

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]);

scanf()function needs the input_format which is a string that will determine


the form of input string. This string is similar to the output_format in the
printf()function.
TOPIC 7 INPUT AND OUTPUT W 82

7.3.1 Variable input

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.

Assume the input entered is:

11 9 2001

Then the printf() statement will print the output as follows:

Day: 11, Month: 9, Year: 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.

/* Program to input 3 name initials and age */


#include <stdio.h>
void main () {
char name1, name2, name3;
int age;
printf(“Enter three characters that represent
your name’s initials”);
scanf(“%c%c%c”, &name1, &name2, &name3);
printf(“Enter your age “);
scanf(“%d”, &age);
printf(“Hello %c.%c.%c”,name1,name2,name3);
printf(“Next year your age will be %d”,age+1);
}
2. If the data input is as follows:
ANSI C?

what is the output of the statements below?


char a, b, c, d, e, f;
scanf(“%c%c%c%c%c%c”, &a, &b, &c, &d, &e,
&f); printf(“%c%c%c%c%c%c”, a, b, c, d, e,
f); printf(“%c%c%c%c%c%c”, a, b, c, d, f, e);
TOPIC 7 INPUT AND OUTPUT W 84

7.4. Summary

• The function printf() is sometimes known as a function to print on the


computer screen.
• Data that is easiest to print or output is a string.
• If a printf() function call has a list of values to be printed, then the
output_format must use the specifications for those values.
• %c specification will be compared to the character value that will be printed.
• Specification %d is used to print integer values whereas %f specification is
used to print real numbers.
• scanf() function allows us to interact with the written program. Input is
from the keyboard.
Unit 8 Operators and
Expressions

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

8.2. Basic arithmetic operators

To enable our programs to do arithmetic calculations, we need arithmetic


operators. Basic arithmetic operator concepts in C language are the same as the
arithmetic operators that were learnt in mathematics in school. Table 8.1 below
shows the operator symbols and examples of basic arithmetic operations in C.
Table 8.1: Operator Symbols and Examples of Basic C Arithmetic Operations

Symbol Meaning Expression Result


+ Add 25 + 8 33
- Minus 120 – 64 56
* Multiply 3 * 7 21
/ Divide 66 / 6 11
% Modulus 66 % 6 0

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

division operator in C is quite different from the normal division operation.


There are two types of division operators, which are the integer division and the
real division. Both types of division use the same operation symbol which is /.
However, the operands differentiate the type of division.

(a) Integer division


Integer division happens when both the operands are of integer type.
Operands can be a constant or a variable. Study the section below:

8/2 /* constant divide constant */


98 / value /* constant divide variable,
value must be of int type */
total / 3 /* variable divide constant,
total must be of int type */
total / count /* variable divide variable,
total and count must be of int type */

Division result of both the operands is determined. If the division is not a


round number (that is it has a decimal value), therefore the remainder of
the division is ignored. The result is truncated to an integer value. Consider
the example given in Table 8.2 below:
TOPIC 8 OPERATORS AND EXPRESSIONS W 87

Table 8.2: Integer Division Operation Example

Operation Calculated Result Result


64 / 8 8 8
12 / 5 2 remainder 2 2
25 / 3 8 remainder 1 8

(b) Real division


Real division is done when one or both of the operands have a real value.
Division operation done is the same as normal arithmetic division. The result
of the division is a real value.

Table 8.3: Real Division Operation Example

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

For each question below, choose the right answer.

1. Consider the program segment below:


int result;
result = 15 / 4;

Which one of the answers given below would keep the value of
result?
A) 3 C) 3.7
B) 3.0 D) 3.75

2. Consider the program code segment below:


printf(“%.0f”, 15 / 4);

Which one of the answers below would be displayed?


A) 3 C) 3.75
B) 3.0 D) None of the above
TOPIC 8 OPERATORS AND EXPRESSIONS W 88

3. Consider the program segment below:


printf(“%.1f”, 15 / 4.0);

Which one of the answers below would be displayed?


A) 3.0 C) 3.75
B) 4.0 D) None of the above

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.

Table 8.4 shows the modulus operation example.

Table 8.4: Modulus Operation Example

Operation Calculated Result Result


5%3 1 remainder 2 2
7%2 3 remainder 1 1
12 % 2 6 remainder 0 0

Activity 8.2

1. Consider the program segment below:


printf(“%d”, 15 % 4);

Which one of the answers below would be displayed?


A) 3 C) 3.7
B) 3.0 D) None of the above

8.3. Arithmetic expressions

C arithmetic expressions are a combination of one or more arithmetic operations.


These arithmetic expressions can represent algebra expressions. Below are a few
examples of arithmetic expressions in C language.
TOPIC 8 OPERATORS AND EXPRESSIONS W 89

5 + 6
14 * 5 * 2
21 - 6 + 7 * 4 / 2
7.5 * (2.0 - 4.52)

Before we can write algebra expressions in C arithmetic expression form, we


need to know how the arithmetic expression is calculated. The most important
thing in evaluating arithmetic expressions is the precedence level.

8.3.1 Precedence level

Precedence level of C arithmetic expressions would determine the arithmetic


operation sequence in solving the problem. For the 5 basic arithmetic operations
that we have seen, the precedence level is as in Table 8.5 below:

Table 8.5: Operator Precedence Levels

Precedence Operation
High *, /, %
Low +, -

Arithmetic expressions are evaluated according to the precedence levels above.


The operators at the high precedence level will be evaluated first. Look at the
example below:

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

What if the precedence levels are the same?


10 % 6 * 3
TOPIC 8 OPERATORS AND EXPRESSIONS W 90

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

8.3.2 Writing arithmetic expressions in c

When we write normal arithmetic expressions (algebra expressions) in the form


of C arithmetic expression, we need to be careful on the precedence levels. If there
is a mistake, the result of the evaluation might not be what we want. Consider
the algebra expression example in Table 8.6 written in C arithmetic expression.

Table 8.6: Changing Algebra Expression to C Expression

Algebra Expression C Arithmetic Expression


14 - 5 + 6 14 - 5 + 6
8
16 - 16 - 8 / 2
2
15 + 5 + 7
(15 + 5 +7) / 2
2

In order to avoid confusion in writing C arithmetic expressions, we use brackets.


In the third example in Table 8.6, if C arithmetic expression is written without
brackets (that is as 15 + 5 + 7 / 2), the result will be different from the
original expression. This expression will be evaluated as:
TOPIC 8 OPERATORS AND EXPRESSIONS W 91

7
15 + 5 +
2

Activity 8.5

Given the algebra expression below:


1
1 + X2

which of these is the equivalent C arithmetic expression?


A) 1/1+x*x C) 1/(1+x*x)
B) 1/1+(x*x) D) 1/(1+x)*x

8.4. Assignment statement (=)

8.4.1 Expression assignment statement

Previously, we have been introduced to assignment statements with values.


Assignment statements can also be used with expressions.

variable = expression;

The expression part of the assignment statement is an arithmetic expression or logic


expression (will be discussed later). The computer will execute this expression (on
the right) and the value is assigned to the variable (on the left). Expression is not
necessarily a constant only. It can be a combination of variables and constants.
Expressions should be able to be calculated. This means that if a variable is used,
that variable should be assigned a value before used in an expression. Consider
example Program 8.1 below:
TOPIC 8 OPERATORS AND EXPRESSIONS W 92

Program 8.1
/* Calculate body weight index */
#include <stdio.h>

void main() {
float weight, height, bodyweightIndex;

weight = 55.5; /* value assignment */ height


= 1.55; /* value assignment */
bodyweightIndex = weight /(height * height);
/* expression assignment */
printf(“Your body weight index is %.2f\n”,
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.

8.4.2 Multiple expression assignment statement

In C assignment statements, other than variables and constants, expressions can


also be other expressions. This means we can do several assignment statements in
one statement just like:

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

x = y = (z = 10) /* assign value 10 to


variable z */
x = (y = (z = 10)) /* expression z = 10 will
have value 10.

This value will be assigned


to y so that y is 10 */
(x = (y = (z = 10))) /* expression value y=z=10 is
assigned to x so that x is
10*/

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.

int age, numOfSiblings;


float weight, height;

/* giving initial values to variables */


age = numOfSiblings = 0;
weight = height = 0.0;

Activity 8.7

Which of these values would be the value assigned to y by the


following statements:
float x, y;
y = x = 10.0 * 2;

A) 10.000000 C) 20.000000
B) 20 D) none of the above
TOPIC 8 OPERATORS AND EXPRESSIONS W 94

8.4.3 Compound assignment statement

In writing programs, sometimes we would like to modify a variable’s value,

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:

weight = weight + 1.5;

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)).

Figure 8.1: Compound statement calculation process [weight=weight+ 1.5]

In C, statements like this can be written using compound operators. Table 8.7
below shows compound operators.

Table 8.7: Compound Operators Example

Operator Example Meaning


+= cnt += 5; cnt = cnt + 5;
-= cnt -= 5; cnt = cnt - 5;
*= cnt *= 5; cnt = cnt * 5;
/= cnt /= 5; cnt = cnt / 5;
%= cnt %= 5; cnt = cnt % 5;
TOPIC 8 OPERATORS AND EXPRESSIONS W 95

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:

points += currentPoints + bonus * currentPoints;

Based on the precedence level, the statement above is solved in this manner:

points + = currentP oints + bonus + currentP oints;


⇔ points = points + currentPoints + (bonus * currentPoints)

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

8.5. Relational operator

Arithmetic operators are used to represent arithmetic formulas to solve problems


that are associated with it. Other than arithmetic operators, C also provides
operators that are used to compare data that is known as relational operators.

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

Table 8.8: Relational Operators Symbols and Relational Expression Examples

Operator Meaning Relational Expression Value


< Less than 6 < 9 1
<= Less than or equal to 12<=13 1
> More than 7>10 0
>= More than or equal to 9 >= 5 1
== Equal to 7 == 5 0
!= Not equal to 6 != 5 1

This operator has 2 operands that can be made up of a variable, constant or a


combination of both. Relational expression is created from a relational operation.
Relational expression will return the value of 1 if true and 0 if false.

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

8.6. Logical operator

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.

Table 8.9: Logical Operator

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

Logical operators can be combined with relational operators to form a compound


expression that is more complex. In evaluating the logical expression, precedence
levels for the relational operator is higher than the logical operator. Assume a =
1, b = 5, c = 15 and d = 25, notice how these logical expressions are
evaluated:

(a) (a >= 1) && (b == 5)


<=> (1 >= 1) && (5 == 5)
<=> 1 && 1
<=> 1

(b) (c >= (b * 3)) ⎥ ⎥ (a == 3)


<=> (15 >= (5 * 3)) ⎥ ⎥ (1 == 3)
<=> (15 >= 15) ⎥ ⎥ (1 == 3)
<=> 1 ⎥⎥ 0
<=> 1

(c) ! (c > a)

<=> ! (15 > 1)


<=> ! 1
<=> 0
TOPIC 8 OPERATORS AND EXPRESSIONS W 98

(d) ! (a < b) ⎥ ⎥ (c > d))


<=> ! (1 < 5) ⎥ ⎥ (15 > 25))
<=> ! ( 1 ⎥⎥ 0 )

<=> ! 1
<=> 0

Activity 8.10

If a= 5, b= 10, c= 15 and validhas the value 1, what is the value of the


expression below?

Expression Result
a) c = = a + b ⎥ ⎥ ! valid
b) a! = 7 && valid ⎥ ⎥ c >= 6

8.7. Increment and decrement operators

Increment and Decrement operators are unique operators. Table 8.11 below
shows the operators.

Table 8.11: Increment and Decrement 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

Table 8.12: Increment and Decrement Expressions

Expression Meaning Statement


i++ i = i + 1 i += 1;
++i i = i + 1 i += 1;
i-- i = i - 1 i -= 1;
--i i = i - 1 i -= 1;

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:

Table 8.13: Sequence of Increment and Decrement Operator

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;

In this statement, the value initially for i (which is 5) is incremented before


(making it 6). Then the new value of i is subtracted by 2; makes j become 4.
This statement is similar to the statement given below:

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 = ?

8.8. Cast operator

Sometimes in an expression, we need to combine different types of variables. In


this situation, C does the variable conversions automatically. That is the type that
is smaller in range is changed to the type that is larger. Automatic changes like this
often happen in arithmetic expressions combining variables of integer and real
type. Observe the example below:
TOPIC 8 OPERATORS AND EXPRESSIONS W 101

int total, count;


float average;
.....
average = total / count;

In the statement average = total / count; we need to calculate the

average value and possibly that the average value is of real type. Therefore, we
will declare the variable average as float type.

When the value of total = 10 and count = 2, therefore average value

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:

average = ((float) total) / ((float) count);

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

Consider the program segment below:


printf(“%f\n”, (float) 15 / 4);

printf(“%.1f\n”, (float)15 / 4);


printf(“%.2f\n”, 15 / (float) 4);

What will be printed?

8.9. Conditional operator

?: operator is known as conditional operator. It is used for evaluating


conditional expressions. The syntax used is:

expression_1 ? expression_2 : expression_3;

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.

expression_1? expression_2 : expression_3


True
False

Consider the following example:

m ? mx + c : c;

In the example above, m value will be determined. If m is true (non- z e r o ), the


value for the entire conditional expression is mx + c. On the other hand, if m is
false, the value for the entire conditional expression will be the value of c.
Therefore, if m is true and we execute the statement:
TOPIC 8 OPERATORS AND EXPRESSIONS W 103

y = m ? mx + c : c;

y will be assigned the value of mx + c. However, if m is false, then y will be


assigned the value of c. The statement above is actually a shorter version of

if (m)
y = mx + c;
else
y = c;

Activity 8.13

1. Consider the program segment below:


int x = 3;
int y = 5;
int min;

printf(“%d\n”, min = y < x? y: x);

What is printed?
2. For each of the algebra expressions below, write the equivalent C
arithmetic expression.

a) b2 - 4ac b) a (b+c)

3. Assume i, j and k are integer variables with i = 5 and j = 3.


What are the values of the following statements?

Expression Value
a) k = j ++;
b) k = i * j-;
c) k = ++ j;
d) k = i * -j;
TOPIC 8 OPERATORS AND EXPRESSIONS W 104

Activity 8.13 ctd

1. Write a program to do the following:


(a) accept the value of temperature in the Celsius unit and change it
to a value in Fahrenheit.
(b) accept the value of a radius and calculate the area and
circumference.

(Use a separate paper to answer these questions)


TOPIC 8 OPERATORS AND EXPRESSIONS W 105

8.10. Summary

• Special arithmetic operators are normally used to write programs.


• Integer division happens when both the operands are of integer type.
Operands can be a constant or a variable.
• Real division is done when one or both of the operands have a real value.
• C arithmetic expressions are a combination of one or more arithmetic
operations.
• Precedence level of C arithmetic expressions would determine the arithmetic operation
sequence in solving the problem.
• Other than arithmetic operators, C also provides operators that are used to compare
data that is known as relational operators.

Potrebbero piacerti anche