0% found this document useful (0 votes)
13 views77 pages

Lecture 2

Uploaded by

techifiafrica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

Lecture 2

Uploaded by

techifiafrica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

CPE 224 : GENERAL COMPUTER PROGRAMMING

OPERATIONS AND EXPRESSION IN C

LECTURE TWO

Department of Computer Engineering


School of Engineering and Engineering Technology (SEET)
Federal University of Technology Minna, Nigeria.
The Program Development Life Cycle
 Programmers follow organized plan or
methodology in trying to write a program:

 Here are the basic steps in trying to solve a


problem on the computer:

1. Problem Definition
2. Problem Analysis
3. Algorithm design and representation
(Pseudocode or flowchart)
4. Coding and debugging
In order to understand the basic steps in solving a
problem on a computer, let us define a single
problem that we will solve step-by-step as we
discuss the problem solving methodologies in detail.
Problem Definition

Before a program can be designed to solve a


particular problem, the problem must be well and
clearly defined first in terms of its input and output
requirements.

A clearly defined problem is already half the


solution. Computer programming requires us to
define the problem first before we even try to
create a solution.
Let us now define our example problem:
“Create a program that will determine the number of
times a name occurs in a list.”

Problem Analysis
After the problem has been adequately defined,
the simplest and yet the most efficient
and effective approach to solve the problem must
be formulated. Usually, this step involves
breaking up the problem into smaller and simpler
sub problems.

Example 1;
Determine the number of times a name occurs in a list
Input to the program: list of names, name to look for

Output of the program: the number of times the


name occurs in a list.

Algorithm design and representation


Once our problem is clearly defined, we can
now set to finding a solution. In computer
programming, it is normally required to express
our solution in a step-by-step manner.
An Algorithm is a clear and unambiguous
specification of the steps needed to solve a
problem.

 It may be expressed in either Human


language through a graphical representation
like a flowchart or through a pseudocode,
which is a cross between human language
and a programming language.

Now given the problem defined in the previous


sections, how do we express our general solution
in such a way that it is simple yet understandable?
Expressing our solution through Human
language:

1. Get the list of names


2. Get the name to look for, let's call this the
keyname
3. Compare the keyname to each of the
names in the list
4. If the keyname is the same with a name
in the list, add 1 to the count
5. If all the names have been compared,
output the result
Expressing our solution through a flowchart:
Expressing our solution through pseudocode:

Let nameList = List of Names


Let keyName = the name to be sought
Let Count = 0
For each name in NameList do the following
if name == keyName
Count = Count + 1
Display Count
 Example 2.

 Class activity involving flowchart and


pseudocode
Example with temperature sensors
Example counting the number of students
that failed an examination
Flowcharting Symbols and their meanings

Process Symbol Represents the process of executing


a defined operation or groups of
operations that results in a change
in value, form, or location of
information.
Input/Output (I/O) Symbol
Represents an I/O function, which
makes data available for processing
(input) or displaying (output)of
processed information.
Decision Symbol
Represents a decision that determines
which of a number of alternative paths
is to be followed.

Terminal Symbol
Represents the beginning, the end,
or a point of interruption or delay in
a program.
Connector Symbol
Represents any entry from, or exit
to, another part of the flowchart.
Also serves as an off-page
connector.
Flowline Symbol Represents the sequence of available
information and executable operations.
The lines connect other symbols, and
the arrowheads are mandatory only
for right-to-left and bottom-to -top
flow.
Annotation Symbol
Represents the addition of descriptive
information, comments, or explanatory
notes as clarification. The vertical line and
the broken line may be placed on the left,
as shown, or on the
Coding and Debugging
After constructing the algorithm, it is now possible
to create the source code. Using the
algorithm as basis, the source code can now be
written using the chosen programming
language.
Most of the time, after the programmer has
written the program, the program isn't 100%
working right away. The programmer has to add
some fixes to the program in case of errors (also
called bugs) that occurs in the program. This
process of is called debugging.
TYPES OF ERRORS
There are two types of errors. The first one is compile-time
error, and the other is runtime error.
Compile-Time Errors occur if there is a syntax error
in the code. The compiler will detect the error and the
program won't even compile. At this point, the programmer
is unable to form an executable that a user can run until the
error is fixed.
Forgetting a semi-colon at the end of a statement or
misspelling a certain command, for example, is a compile-
time error. It's something the compiler can detect as an error.
Compilers aren't perfect and so can't catch all errors at
compile time.
This is especially true for logic errors such as infinite loops.
This type of error is called runtime error.
Number Systems and Conversions
 Numbers can be represented in a variety of
ways. The representation depends on what is
called the BASE.
 The following are the four most common
representations.
1. DECIMAL
 We normally represent numbers in their decimal
form. Numbers in decimal form are in base 10.
This means that the only digits that appear are
0-9.
 Here are examples of numbers written in
decimal form:
12610 (normally written as just 126)
2. BINARY
 Numbers in binary form are in base 2. This means that the
only legal digits are 0 and 1.
 We need to write the subscript 2 to indicate that the
number is a binary number. Here are examples of
numbers written in binary form: (1) 11111102 (2)
10112

3. OCTAL
Numbers in octal form are in base 8. This means that the
only legal digits are 0-7. We
need to write the subscript 8 to indicate that the number is
an octal number. Here are
examples of numbers written in octal form:
(1) 1768 (2) 138
4. HEXADECIMAL
 Numbers in hexadecimal form are in base 16.
 This means that the only legal digits are 0-9
and the letters A-F (or a-f, lowercase or
uppercase does not matter).
 We need to write the subscript 16 to indicate
that the number is a hexadecimal number.
Here are examples of numbers written in
hexadecimal form:7E16, B16
Hexadecimal: 0 1 2 3 4 5 6 7 8 9 A B C D E F

Decimal Equivalent: 0 1 2 3 4 5 6 7 8 9 10 11 12
13 14 15
Conversions
1. Decimal to Binary / Binary to Decimal
Example 1:
12610 = ? 2

QUOTIENT REMAINDER
126 / 2 = 63 0
63 / 2 = 31 1

THIS WAY
WRITE IT
31 / 2 = 15 1
15 / 2 = 7 1
7/2= 3 1
3/2= 1 1
1/2= 1
So, writing the remainders from the bottom up,
we get the binary number 11111102
For Example:
11111102 = ? 10
Position 6543210
Binary
Digits 1111110
0
0x2=0
1
1x2=2
2
1 x 23= 4
1 x 2= 8
4
1 x 2= 16
5
1 x 2 = 32
6
1 x 2 = 64
TOTAL: 126
Decimal to Octal (or Hexadecimal)/Octal (or
Hexadecimal) to Decimal

Example2. (Octal):
12610 = ? 8
QUOTIENT REMAINDER
126 / 8 = 15 6
15 / 8 = 1 7
1/8= 1
For Example (Hexadecimal):
12610 = ? 16

THIS WAY
WRITE IT
126 / 16 = 7 14 (equal to hex
digit E)
7 / 16 = 7
7E16
Converting octal or hexadecimal numbers to
decimal is also the same as converting binary
numbers to decimal.
Binary to Octal / Octal to Binary
To convert from binary numbers to octal, we
partition the binary number into groups of 3
digits (from right to left), and pad it with zeros
if the number of digits is not divisible by 3.
We then convert each partition into its
corresponding octal digit. The following is a
table showing the binary representation of
each octal digit.
Octal Digit Binary Representation
Octa digit Binary representation
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
For Example:
11111102 = ? 8
001 111 110

1 7 6 Equivalent octal number


Binary to Hexadecimal / Hexadecimal to
Binary

To convert from binary numbers to


hexadecimal, we partition the binary number into
groups of 4 digits (from right to left), and pad it
with zeros if the number of digits is not divisible
by 4.
We then convert each partition into its
corresponding hexadecimal digit.
The following is a table showing the binary
representation of each hexadecimal digit.
Hexadecimal Digit Binary Representation

0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111
For Example:

11111102 = ? 16
0111 1110

7 E
Equivalent Hexadecimal
number
QUESTIONS
EASY ONES
ONLY
Exercises
Writing Algorithms
Given the following set of tasks, create an algorithm to
accomplish the tasks.
You may write your algorithms using pseudocode or you
can use flowcharts.
1. Producing
2. Logging into your laboratory's computer
3. Getting the average of three numbers
Number Conversions
Convert the following numbers:
1. 198010 to binary, hexadecimal and octal
2. 10010011012 to decimal, hexadecimal and octal
3. 768 to binary, hexadecimal and decimal
4. 43F16 to binary, decimal and octal
INTRODUCTION TO C
• C is a general purpose, structured programming
Language.
• It consist of terms that resembles algebraic
expressions, augmented by certain English
keywords such as if ,else, for do while etc.
• C also contains certain additional features that
allows it to be used at lower level, thus bridging the
gap between the machine language and the High
level language.
• C is highly flexible, thus making it suitable for
system programming as well as application
programming.

29
29
HISTORY OF C

• Developed in the 1970’s at the Bells Laboratory (AT&T


LAB now) by Dennis Ritchie.

• Until 1978 C was not for commercial use.

• However, in 1978 the commercial Version was


available after the work on earlier version by Brian
Kennighan and Dennis Ritchie forming the K&R C.

• It was then used to rewrite the Unix operating system.

30
30
More on C Language
 Many programming languages have been fully or
partially written in C including C++, Java, C#, Perl,
Python, PHP and many more.

 C programs are portable across Oss (source codes not


executable files)

 C is extensible (users can add their own functions to the


existing library)
STRUCTURE OF THE C PROGRAM
• Every C program consist of one or more modules
called functions.
• The most important of the function is called the main
function.
• The program execution begins at the main function and
then other functions which would be declared
separately.
• Each function must contain the following;
• A function heading(the function name and
argument)
• List of argument Declaration
• A compound statement.
32
32
General structure of C program
Comments
Preprocessor Directives
Global Variables
main() {
Local Variables
Statements
}
Other Functions
C program
It consist of the following
 Preprocessor : #include <stdio.h> (header)
Functions : May be more than one , but specifically one of the
functions must have a main function
Each function : must have a name , followed by list of arguments
enclosed in parentheses. { }
Comment entered by (/* */) these are not compiled along the
complete program. They are only used by programmers for the ease
of describing what the program does.

34
34
C Characters

The character sets in C


 The building blocks in C in the formation of Program
elements consist of characters could be in any of the following
forms
Upper Case A –Z
Lower Case a-z
Digits 0-9
Special character : & % $ @ , -,+,=,[,], _,”,;,:,* ^, ?, /, etc
Combinatory Characters: \b (backspace), \n (newline), \t
(horizontal tab), \a (alert sound) /* ( comment ). etc
Note : the (\) is called an escape character. Which means the
compiler should be something out of the ordinary. Whenever
the compiler see this \ string it looks ahead at the next
character and combines it with the \ to form an Escape
Sequence.
Quick Review
Tokens
 Basic elements inside a C program that the compiler can
identify
 Types
 Identifiers/Variables
 Keywords
 Constants
 Operators
 Strings
Identifiers and Keywords

 There are two types of words used in a C program. They are


either system defined or user defined words. The system
defined words are known as keywords while the user defined
words are known as identifiers (also known as Variables).
Identifiers
C language specifies some rules for naming an identifier
 Identifier names can only have alphabets, underscore (_) and
digits.
 The name should start with an alphabet or underscore.
 Predefined keywords cannot be used as an identifier.
 C language is case-sensitive. Therefore uppercase and
lowercase names are considered separate.
 Most of the C compilers support identifiers up to 31
characters. However it is advised to keep the names short and
meaningful.
Identifiers
Examples includes : x, y23, _mydata, k12my, TABLE
tax_money etc.

Example of wrong identifiers:

4th, 5th Only letters or underscore can start an


identifier

 ‘p’, unacceptable character for identifier (‘)

 order-number. unacceptable character for identifier (-)

 error page. unacceptable character for identifier (blank


space)
keywords

These are sets of reserved words in C, they have


predefined meaning and can not be changed. They can not
be used as a programmer defined identifier.

Note : most often keywords are all lower case. But it is a


very bad programming practice for you to use the upper
cases as identifiers.
Quick Review
DATA TYPES
Classified into four
Basic type
Enum type
Derived type
Void type
BASIC DATA TYPES

Basic types are used to define integer and floating-point


numbers

Int - integer quantity 2 byte or word


Char -single character 1 byte
Float -floating –point number 1 word
Double -Double precision floating point (more
significant figures ) -2 words
Most often the data types requires qualifiers to be added
to them.
Examples of Qualifiers includes: short, long, unsigned,
signed , etc
Data Types

short
Long
Unsigned
Signed

CONSTANTS
There are basically four(4) types of constants in C
The integer constants -Numeric constants
Floating point -Numeric constants
Character constants and the string constant
 Enumerated types are created using the enum
keyword. They are used to assign integer values to the
words which can be used later in the program

 Derived data types uses the basic data types to create


more versatile data types. E.g. arrays, pointers,
structure, function etc.
 Void means no value
 As a return type to a function void main()
 As function argument void main (void)
Variables and Arrays

VARIABLES AND ARRAYS


Variables are identifiers that are used to represent some specified type
of information within a designated portion of the program .
In the most basic form , a variable is an identifier that is used to
represent a single data item. (character or numeric)
The data must be assigned to the variable at some point in the
program.

 variable syntax : data type variable


Int a,b,c;
Char d;
A=3;
B=9;
C=A+B;
d= ‘C’
Variables and Arrays
Array : Is another kind of variable that is used most often in C.
An Array is an identifier that refers to a collection of data that all
have the same name .
The data item must all have same type. (all integer, all
characters, all float, etc)
The individual data item are represented by their corresponding
array elements (first data item is represented by the first array
element )
The individual array elements are distinguished from one another
by the value that is assigned to a subscript. (index)

X={}
 first element X[1], second element X[2]
There are many ways the array can be represented by the one
dimensional may be ok for our level now.
Declarations
Declarations basically associates groups of the variables with specific
data types. (allocate memory)
Makes use of variables , data types .
All variables must be declared before they can appear or used in
executed statements .

The data type decides the type and range of values that a variable can
store.

Syntax : data types variables


 int a, b, c ;
float root1, root2;
Variable Iinitialization

Initial values can also be assigned to variables with a type


declaration. (when not initialized, they contain garbage in the
memory location).
To do this , the declaration must consist of a data type , a variable
name , an equal to sign (=) and then a constant of an appropriate
type. And thereafter a semicolon must appear at the end as a
normal and usual practice.

 int cpe = 23;


Short int zyn =143;
char text[]= ‘FutMinna’
char text[8]= ‘FutMinna’ /* it also correct*/
char text[20]= ‘Gidankwanu’ /* the remaining element will be
assumed/assigned to be zero*/
Expressions

An expression represents a single data item, such as number or


character.
May be single entity such as constant , variable or an array or even
a function.
It may also be combinatory
Expressions can also represents logical conditions that are either
true or false.
Basically in C true is represented by integer 1 and false by integer
0. Examples of simple expression includes;,
 a+b
X=y
C=a+b
X>=y
Y<=v
X==Y
Statements

Statement generally will make the compiler or pc to execute or


carry out some actions.

Statements are basically of 3 major types namely: Expression


statement, Compound Statement and Control Statement.

EXPRESSION : thus statement consist of an expression followed


by semicolon. The execution of an expression statement causes the
expression to be evaluated.
a-=3;
c=a+b;
++i;
; /* null statement does not do anything*/
 COMPOUND : just as the name is, the compound statement consist
of several individual statements enclosed within a pair of braces {}
statements

STATEMENTS (compound)
 The individual statements may themselves be expression statement,
compound statements or even control statements.
The compound statement provides a capability for embedding
statements within other statement.
Unlike the expression statements, a compound statement does not end
with a semi colon.

Examples
{
pi=3.142;
circum=2.*pi* rad;
area=pi*rad*rad;
}
statements
STATEMENTS
CONTROL STATEMENT
This statement basically the most important of all statements as it help in
creating special program features such as logical test, loops and branches .

The for loop, while loop, if-else ,, etc are used to form the control statement.

SYMBOLIC CONSTANTS
 Symbolic constant is a name that substitutes for a sequence of characters.
The characters may represent a numeric constant , a character constant or a
string constant.
A symbolic constant allows a name to appear in place of a numeric constant
or character.
Symbolic constant are usually defined at the beginning of a program.
Syntax : #define name text
#define taxrate 0.23
#define passrate 100
QUIZ
OPERATORS AND EXPRESSIONS

OPERATORS (classified based on number of operands or


the operation they perform)
Arithmetic Operators
Unary Operators
Relational and Logical Operators
Assignment Operators
Conditional Operators

Basically the operators needs Data to act upon in order to produce a


particular result .
This Data that operators act upon are called the OPERANDS

A+b ; A and b are the operands while + is the operator.


OPERATORS AND EXPRESSIONS

Arithmetic Operators
There are FIVE arithmetic Operators in C

 % is called the modulus operator


It is the reminder of a division operation.
So what operator is used for exponential operation.? C does not
have but the pow function in the library is used for this operation.
OPERATORS AND EXPRESSIONS

Arithmetic Operators
Operands acted upon by arithmetic operators must represent NUMERIC
values.
Operands can be of any data type : float integer, characters etc.
 % : requires that both operand must be integers and the second must be
nonzero
 /: the second operator must not be zero.
Examples: a=20 , b =8
 a+b
 a-b
 a*b
 a%b
a+b*2
(a+b)*2 note the precedence between + and *(higher precedence)
OPERATORS AND EXPRESSIONS

Arithmetic Operators
Examples: a=10, b =-4 but if a=-10 , b=4 modulus will be -2

 a+b
a-b
 a*b
 a%b =2
 a/b =-2

 a= ((a/b)*b) + (a%b) ?
OPERATORS AND EXPRESSIONS

Arithmetic Operators
 Some rules applies to when performing operation on unsigned
operators
SUMMARY OF THE RULES
 int (char, short or long)+float=float
 float+double=double
 Float+long double=long double
 double+long double=long double
 int+double=double
 Int+long int=long int
 short int +int = int
OPERATORS AND EXPRESSIONS

Arithmetic Operators
The value of an expression can be converted to a different data type
if desired . To do so the expression must be preceded by the name of
the desired data type enclosed in parentheses.

 (data type ) expression /* this is called a cast */

Example
If i= 7 (integer) , and f= 8.5 (float)

(i+f)%4 /* invalid because the i+f is a float , thus modulus may not
be possible */

(int)(i+f)%4 /* valid now , forces the i+f to be an integer*/


NOTE : the cast does not change the expression but rather the value of
the expression.
OPERATORS AND EXPRESSIONS

Arithmetic Operators
Precedence : the order of evaluation. The operation with a higher
precedence is carried out first before those of lower precedence . But
this precedence can be altered through the use of parentheses.

 *. / AND % : HIGHER Precedence group


 + and - : Lower precedence.

UNARY OPERATORS
Unary operators are operators that act upon a single operand to
produce a new value.
Unary operators usually precede their single operand, though some
unary operators are written after their operands
OPERATORS AND EXPRESSIONS

UNARY Operators
Unary Minus : (-) formed when a numerical constant , variable or
expression is preceded by a minus sign.
Note : unary minus is completely different from subtraction.
 Example
 -743
-root1
 -(x+y)
 -3*(x+y)

Increment Operator : (++) causes its operand to be increased by 1.


Decrement Operator : (--) causes its operand to be decreased by 1
The operator that uses these operators must be a single variable.
OPERATORS AND EXPRESSIONS

UNARY Operators
 if i=5 , so the expression ++1 , which is equivalent to
i=i+1 = 6
Similarly -- 1 , is equivalent to
i=i-1= 4.
e.g
a=20, b=8;
c=a++ +b;
c=--a+b;

 Sizeof : the sizeof is also a unary operator, it returns the size of its
operand in byte. It is usually used in form of a cast .

Note : Unary operator have a higher precedence than arithmetic


operators.
OPERATORS AND EXPRESSIONS

Relational and Logical Operators


There are basically FOUR relational operator in C

All relational operators have the same other of precedence , which is


lower than that of arithmetic and unary operators.
The associativity of these operator is left to right (means it is executed
from left to right)
OPERATORS AND EXPRESSIONS

Relational and Logical Operators


There are also equality operator

The equality operator fall into a separate precedence group, beneath


the relational operators
The associativity of this operator is left to right (means it is executed
from left to right)
OPERATORS AND EXPRESSIONS

Logical Operators
This operators represents condition that are either true or false.
The resulting expression will be of type integer since true is represented
by the integer value 1 and false by integer 0
OPERATORS AND EXPRESSIONS

Logical Operators
Lets see some Logical operations

Where i=1, j=2, and k=3 .


OPERATORS AND EXPRESSIONS

Logical Operators (OR and AND )


 LOGIC OR ( ||)
LOGIC AND ( &&)

These Logical operators act upon operands that are themselves logical
expressions. The overall resultant is to combine the individual logic
expressions into more complex conditions that are either true or false.
The result of a logical AND operation will be TRUE if both operands
are true .
While the result of a logical OR operation will be TRUE if any of the
operands is true.

i=7 , f=5.5

(f<11)||(i>100)
(f>11)&&(i>100)
OPERATORS AND EXPRESSIONS

Logical Operators (OR and AND )


 Precedence: The logic and && has a higher precedence than the logic OR ||, but both has a
lower one than the equality.

Another logical operator is the logical Negation (Logical NOT ). We can see that it is a unary
operator.

Logical NOT (!)


If (f>5) is TRUE
Then !(f>5) is what ?
More examples on logical operators
 int a=5, b=4, c=6, d=0; Outputs
 printf(“%d”, a==b); 0
 printf(“%d”, a<=c); 1
 printf(“%d”, d&&b); 0
 printf(“%d”, a||d); 1
 printf(“%d”, a!=b); 1
 printf(“%d”, !c); 0
OPERATORS AND EXPRESSIONS

Logical Operators (OR and AND )


 Precedence: let see some of it
OPERATORS AND EXPRESSIONS

Assignment Operators (=)

 Identifier =expression

Of course we know the identifier has to be a variable and the


expression can as well be a variable or constant or a more
complex expression.

Note there is a difference between = and = =


= is an assignment operator : used to assign a value to an
identifier
== is an equality operator : used to determine if 2 expression
have the same value
OPERATORS AND EXPRESSIONS

Conditional Operators (? : )
 When an expression make use of these operators it is known as
Conditional expression

Conditional operators can be used in place of the conventional if-else


statement (you will study this under the control structure)

Syntax : expression 1 ? expression 2 : expression 3

When evaluating a conditional expression , expression 1 is evaluated


first . If its true , then expression 2 is evaluated and this becomes the
value of the conditional expression.
However if expression 1 is false , then expression 3 is evaluated and
that becomes the value of the conditional expression
OPERATORS AND EXPRESSIONS

Conditional Operators (? : )
 example

(i<0) ? 0 : 100

(i<0) is evaluated first , if its true then the


expression takes the value of 0

Else the expression takes the value of 100.


LIBRARY FUNCTIONS

You might also like