You are on page 1of 11

1/15/2017

To learn how to write a C program,


lets look at
some concepts.

Contents
Six Basic Computer Operations
Constants and variables
Local and global variables
Meaningful data names
Data types
Operators
Expressions and equations
Functions

Learning Outcome
Differentiate between constant data and variable data
with different data types.
Differentiate between variables and constants.
Differentiate between character, numeric and
logical data types.
Identify operators, operands, and resultants.
Identify and use operators according to their
precedence.
Set up and evaluate expressions and equations.
Understand and use pre-defined functions.
References:
Problem Solving and Programming Concepts (9th Edition) . Maureen Sprankle, Jim Hubbard, Pearson Education Limited 2012.

1
1/15/2017

Six Basic Computer Operations 1. A computer can receive Information


1. A computer can receive information.
When a computer is required to receive information or
2. A computer can put out information. input from a particular source, whether it is a terminal, a
disk or any other device, the verbs Read and Get are
3. A computer can perform arithmetic.
used in pseudocode.
4. A computer can assign a value to a variable or
memory location.
5. A computer can compare two variables and select one
or two alternate actions.
6. A computer can repeat a group of actions.

2. A computer can put out information 3. A computer can perform arithmetic


Most programs require the computer to perform some
When a computer is required to supply information or sort of mathematical calculations, or formulae, and for
output to a device, the verbs Print, Write, Put, this purpose, a programmer may use either actual
Output, or Display are used in pseudocode. mathematical symbols or words for those symbols.
To be consistent with high-level programming
Usually an output Prompt instruction is required before languages, the following symbols can be written in
an input Get instruction. pseudocode:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
( ) for Parentheses

4. A computer can assign a value to a 5. A computer can compare two variables and
variable or memory location select one or two alternate actions
There are three cases where you may write pseudocode An important computer operation available to the
to assign a value to a variable or memory location: programmer is the ability to compare two variables and
then, as a result of the comparison, select one of two
1. To give data an initial value in pseudocode, the alternate actions.
verbs Initialize or Set are used.
To represent this operation in pseudocode, special
2. To assign a value as a result of some processing the keywords are used: IF, THEN, and ELSE
symbols = is written.

3. To keep a variable for later use, the verbs Save or


Store are used.

2
1/15/2017

6. A computer can repeat a group of actions


When there is a sequence of processing steps that need
to be repeated, special keywords, DO,DOWHILE and
ENDDO, are used in pseudocode.

The condition for the repetition of a group of actions is


established in the DOWHILE clause, and the actions to
be repeated are listed beneath it.

How do we store data in a program? Constants and Variables


Data can be stored within a program as a single A constant is a value that is, a specific alphabetical
variable, such as an integer or a character, or a group and/or numeric value that never changes during
items (sometimes called an aggregate), such as an the processing of all the instructions in a solution.
array, a structure, or a file. E.g. #define PI 3.14159265

In contrast, the value of a variable may change


during processing. In many languages, variables are
called identifiers.

Local and Global Variables


Global declaration
Variables declared at this section is visible to all
parts of the program.

Local declaration
Variables declared in a certain function.
Visible only to the functions that contain them.

3
1/15/2017

Data naming convention


Name a variable according to what it represents
(meaningful names).
Do not use spaces in a variable name.
Start a variable with a letter.
Do not use any mathematical operator in a variable name.
Be consistent when using upper and lower case characters.
Do not use system reserved words.

Examples of Incorrect Variable Names


Importance of Naming Convention Data Item Incorrect Problem Correction
Allows several programmers to work on the same Variable Name
project without conflict in using variable names.
Allows program to be easily read due to consistency of Hours worked hours worked Space between hours_worked
words
variable names within a company.
Codes can be easily maintained.
Name of Client cn Does not define client_name
Software performs more efficiently. data item
Increase performance expectation.
Produce clean, well-written programs. Rate of pay pay-rate Using pay_rate
mathematical
operator

Exercise: Incorrect Variable Names


Data Item Incorrect Variable Problem Correction
Name

Quantity per Quantity/customer


customer
6% sales tax 6%_sales_tax

Client address Client_address_for_cli


ent_of_XYZ_Corporati
on_in_California
Hours worked Hour worked

Break time break

4
1/15/2017

Data Types
1. Primitive Data Types
Data are unorganized facts.
A primitive data item is one containing a single
At the beginning of a program, the programmer must variable that is always treated as a unit.
clearly define the form or type of data to be collected
for the variables created. A data type consists of a set of data values and a set of
operations that can be performed on those values.
The data types can be:
Primitive Data Types, or The most common elementary data types are:
Composite Data Types integer * character * boolean
float * double

1. Data Type - Numeric


2. Composite Data Types
The data items that it contains are its components,
which may be primitive data items or another data
Numeric data
structure.
Integer
Float
The most common data structures are:
* Records Integer: whole number, such as 5297 or -367 which can be
* File (for permanent storage) positive or negative.
* Array Float: real numbers, which are whole numbers plus
decimal parts. E.g. 3.671234
* String

2. Data Type Character/Alphanumeric


ALL single digit numbers, letters, and special characters 3. Data Type Logical/Boolean
available in computer. (placed within quotation marks) Hold only two values true or false.
E.g. A, a, 1, @, #, +
Implementation in programming languages may
Uppercase and lowercase letters are considered
differ. E.g. T, F, yes, no, 0, 1, etc.
different characters.

Variables declared as characters cannot be used for Mainly used as a control flag or a switch.
calculations. E.g. A+ 1 = ??? E.g.
One or more characters can be combined into a credit_ok = true
string. E.g. : a, abc, Hello World 123 !! cheque_cleared = Y

5
1/15/2017

3. Data Type: Examples 3. Data Type: Examples (cont)

float

A a M z k
1 5 7 8 0
+ = ( % $

3. Data Type: Examples (cont)


Rules for Data Types
Most commonly used data types: numeric (integer
and float), character (including string), and logical.
A programmer designates the data type during
programming process.
Numeric data types are used for numeric item
calculations. Other numeric items should be
designated in character or string data types even if
data are all numbers. E.g. zip code.

Why Must Input Be Validated?


Data Validation
Risks of data entry errors are high due to:
Data should always undergo a validation check before
it is processed by a program. Large volume of data entered.
Human error keying in data.

Different types of data require different checks for


example: Invalid input leads to inaccurate output.
* Correct type E.g., salary reported incorrectly if a datum is entered
* Correct range as 23000 instead of 32000.
* Correct length
* Completeness Input errors can cause program interruptions.
* Correct date E.g., spaces entered for numeric field used in
arithmetic operation can cause errors.

6
1/15/2017

Operators
Data is connected with expressions and equations.
Operators tell computer how to process data.
Types of processing that can be done include:
Mathematical (standard mathematical operations)

Relational (to program decisions)

Logical
to connect relational expressions
to perform operations on logical data

Operators and Computer symbol Relational Operator Result

Mathematical Operator Result


Equal to = 5=6 FALSE
Less than < 5<7 TRUE
Addition + 3+5 8 Greater than > 3>1 TRUE
Less than
Subtraction - 7.5 - 2 5.5 or equal to <= 3<=3 TRUE
Greater than
Multiplication * 4 * 2.5 10 or equal to >= 4>=7 FALSE
Not equal to != 5!=3 TRUE
Division / 60 / 3 20
Logical Operator Result
modulo division % 13 / 7 6 Not ! ! True FALSE
And && true AND false FALSE
Or || true OR false TRUE

Operator and Computer Symbol C Operator Precendence Table


Example
int a=5;
float b=3.2;
Operator Description Associativity
printf(\n a=%d \t b=%.2f \n, a, b);
() Parentheses: grouping or function call left-to-right
a=5+6; (variable a will hold value =11)
++ -- Postfix increment/decrement
printf(\n a=%d \t b=%.2f \n, a, b);
right-to-left
a=5%2; (variable a will hold value =1) ++ -- Prefix increment/decrement
printf(\n a=%d \t b=%.2f \n, a, b); ! Logical negation
b=5/2.0; (variable b will hold value =2.500000) (type) Cast (convert value to temporary value of type)
printf(\n a=%d \t b=%.2f \n, a, b); sizeof Determine size in bytes on this implementation
b+=3; ( b=b+3)
printf(\n a=%d \t b=%.2f \n, a, b);
a-=2; (a=a-2)
printf(\n a=%d \t b=%.2f \n, a, b);

7
1/15/2017

C Operator Precendence Table

Operator Description Associativity


* / % Multiplication/division/modulus left-to-right

+- Addition/subtraction left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= Modulus assignment

Expressions and Equations


Expression
An expression processes data (the operand) with the
use of operators. E.g.
length * width

Equation
An equation stores the result of an expression in a
memory location through the equal (=) sign which is
called the assignment operator. E.g.
area = length * width

Setting Up Expression and Equation Evaluating a Mathematical Expression

Examples: In C program:

X(3Y+4) 4Y X*(3*Y+4) 4*Y/(X+6)


X+6

Y + 3 is equal to X(Z + 5) Y + 3 == X * (Z + 5)

X is less than Y + 5 X < (Y + 5)

8
1/15/2017

Evaluating a Relational Expression Evaluating a Logical Expression


If A = 3 and B = 7, If A = True, B = False and C = True,

Functions
Q: Why we need to have several functions in a program?
A: There are actually many reasons for creating more than
one functions in a program. As we learn along, you will
know the reasons behind this. But for the moment, just try
to imagine if is it better to have one person to do all the
jobs? Or have several people to split the jobs?

Functions Types of Functions


Creating different functions in a program is like having Predefined Functions
different departments in a company. Usually built in with the compiler.
In real life, a company will have different departments. Written by the developer to solve some common tasks.
Each department specializes in performing certain tasks.
E.g. HR department handles employee-related tasks.
Finance department handles the company funds. Self-defined Functions (chapter 4)
In programming, each function is specially designed to In most situations, we cant solve all problems by using
solve different problems. pre-defined functions. We need to write our own
functions.
A customized instructions written by ourselves are
known as Self-defined Functions.

9
1/15/2017

Predefined Functions Predefined Functions (cont)


Mathematical functions. Conversion functions.
Contains most of the science, business and mathematical Used to convert data from one data type to another .
functions such as square root, random numbers and power.
Statistical functions.
Used to perform calculations such as maximum values,
String functions. minimum values, and so forth.
Used to manipulate string, e.g. copying part of the string into
another variable, or finding the length or the number of Utility functions.
characters in the string.
Used to access information outside the program and the
language in the computer system, including date and time
functions.

Predefined Functions (cont) Predefined Functions (cont)

Predefined Functions (cont) Predefined Functions (cont)

10
1/15/2017

Summary
Six Basic Computer Operations
Constants and variables
Local and global variables
Meaningful data names
Data types
Operators
Expressions and equations

11

You might also like