ccs-2101-introduction-to-programming-in-c-notes-1-3-1
ccs-2101-introduction-to-programming-in-c-notes-1-3-1
Introduction
Literally speaking, a language is a vehicle of communication amongst human beings.
To communicate, a given procedure is followed which may normally be dictated by grammar.
A computer language is not very different. Computers do not understand any of the natural languages for
transfer of data and instructions. So there are languages specially developed so that you could pass your
data and instructions to the computer to do a specific job.
This chapter introduces structured approach to programming which the rest of this guide is all about. The
chapter also presents a quick overview of C language. The goal is to give you sufficient working
knowledge of C language so that you can understand more concrete concepts in later chapters.
Programming defined
Programming is the translation of user ideas into a representation or form that can be understood by the
computer. The tools of writing programs are called programming languages.
Editing
You write a computer program with words and symbols that are understandable to human beings. This is
the editing part of the development cycle. You type the program directly into a window on the screen and
save the resulting text as a separate file. This is often referred to as the source file. The custom is that the
text of a C program is stored in a file with the extension .c for C programming language e.g. hello.c
1
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Compiling
You cannot directly execute the source file. To run on any computer system, the source file must be
translated into binary numbers understandable to the computer's Central Processing Unit. This process
produces an intermediate object file - with the extension .obj e.g hello.obj
Compiling
Regardless of the HL Language, all HL programs need to be translated to machine code so
that a computer can process the program.
Some programs are translated using a compiler. When programs are compiled, they are
translated all at once. Compiled programs typically execute more quickly than interpreted
programs, but have a slower translation speed.
Interpreting
Some programs are translated using an interpreter. Such programs are translated line-by-line
instead of all at once (like compiled programs). Interpreted programs generally translate
quicker than compiled programs, but have a slower execution speed.
Linking
The main reason for linking is that many compiled languages come with library routines which can be
added to your program. Theses routines are written by the manufacturer of the compiler to perform a
variety of tasks, from input/output to complicated mathematical functions. In the case of C the standard
input and output functions are contained in a library (stdio.h) so even the most basic program will require a
library function. After linking, the file extension is .exe which is an executable file e.g. hello.exe
You can then run .exe files as you run applications, simply by typing their names at the DOS prompt or run
using Windows menu.
Algorithm
An algorithm is a procedure or formula for solving a problem.
A specific set of instructions for carrying out a procedure or solving a problem, usually with the
requirement that the procedure terminate at some point.
A set of instructions that leads to a predictable result
An algorithm is programming language independent
2
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Example
Write an algorithm to determine a student’s final grade and indicate whether it is pass or fail. The final
grade is calculated as the average of four marks. Fail is average below 50
Start
Step 1: Input M1,M2, M3, M4
Step 2: GRADE = (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then Print “FAIL”
Step 4: if (GRADE > 50) then Print “PASS”
Stop
Characteristics of algorithm
i. Finiteness-An algorithm must terminate after a finite number of steps and further each step must be
executable in finite amount of time.
ii. Each step of an algorithm must be precisely defined; the action to be carried out must be rigorously
and unambiguously specified for each case.
iii. Input: An algorithm has zero or more, but only finite number of inputs.
iv. Output: An algorithm has one or more output.
v. Effectiveness: Should be effective that means each of the operation to be performed in an algorithm
must be sufficiently basic that it can, in principle, be done exactly and in a finite length of time, by
a person using pencil and paper and should be computer programming language independent
The Flowchart
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their interconnections e.g. control flow from one action to the next
3
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Example 1
Draw a flowchart to find the sum of the first 50 natural numbers.
Algorithm
Start.
Step 1: Initialize n and sum to zero (n=0; sum=0).
Step 2: Add 1 to n (n=n+1).
Step 3: Add n to sum (sum=sum + n).
Step 4: Is n=50? If no go to step 2.
Step 5: Print sum.
Stop.
Flowchart
Example 2
Draw a flow chart to determine a student’s final grade and indicate whether it is fail or pass. The final
grade is calculated as the average of four marks. Fail is average below 50
4
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
i. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
ii. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
iii. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
iv. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
v. Proper Debugging: The flowchart helps in debugging process.
Advantages of C Language
i. C Supports structured programming design features - It allows programmers to break down their
programs into functions. It also supports the use of comments, making programs readable and
easily maintainable.
ii. Efficiency - C is a concise language that allows you to say what you mean in a few words. The final
code tends to be more compact and runs quickly.
iii. Portability - C programs written for one system can be run with little or no modification on other
systems.
iv. Power and flexibility
Power - C has been used to write operating systems (such as Unix and Windows), Language
Compilers, Assemblers ,Text Editors, Print Spoolers, Network Drivers, Application packages (such
as WordPerfect and Dbase), Language Interpreters, Utilities, etc.
Flexibility-It has (and still is) been used to solve problems in areas such as physics and engineering.
v. Programmer orientation - C is oriented towards the programmer’s needs. It gives access to the
hardware. It lets you manipulate individual bits of memory. It also has a rich selection of operators
that allow you to expand programming capability.
5
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
C Program components
Keywords
These are reserved words that have special meaning in a language. The compiler recognizes a keyword as
part of the language’s built – in syntax and therefore it cannot be used for any other purpose such as a
variable or a function name. C keywords must be used in lowercase otherwise they will not be
recognized.
Examples of keywords
Example
This program will print out the message: This is a C program.
#include<stdio.h>
main()
{
printf("This is a C program\n");
return 0;
}
#include<stdio.h> allows the program to interact with the screen, keyboard and file system of your
computer.
main() declares the start of the function. This is the start point of the program.
The two curly brackets ({ }) show the start and finish of the function. They are used to group
statements together as in a function, or in the body of a loop. Such a grouping is known as a compound
statement or a block.
printf("This is a C program \n"); prints the words on the screen. The text to be printed is enclosed in
double quotes. The \n at the end of the text tells the program to print a new line as part of the output.
Most C programs are written in lower case letters. You will usually find upper case letters used in
preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings.
C is case sensitive, that is, it recognizes a lower case letter and it's upper case equivalent as being different.
6
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Functions
All C programs consist of one or more functions, each of which contains one or more statements. In C, a
function is a named subroutine that can be called by other parts of the program. Functions are the building
blocks of C.
A statement specifies an action to be performed by the program. All C statements must end with a
semicolon.
Although a C program may contain several functions, the only function that it must have is main( ).
The main( ) function is the point at which execution of your program begins. That is, when your program
begins running, it starts executing the statements inside the main( ) function, beginning with the first
statement after the opening curly brace. Execution of your program terminates when the closing brace is
reached.
Another important component of all C programs is library functions. The ANSI C standard specifies a
minimal set of library functions to be supplied by all C compilers, which your program may use. This
collection of functions is called the C standard library. The standard library contains functions to perform
disk I/O (input / output), string manipulations, mathematics, and much more. When your program is
compiled, the code for library functions is automatically added to your program.
One of the most common library functions is called printf( ). This is C’s general purpose output function.
Its simplest form is
printf(“string – to – output”);
In C, one or more characters enclosed between double quotes is called a string. The quoted string between
printf( )’s parenthesis is called an argument to printf( ). In general, information passed to a function is
called an argument.
In the above program, line 6 causes the message enclosed in speech marks “ ” to be printed on the screen.
Line 7 does the same thing. The \n in line 7 tells the computer to insert a new line after printing the
message. \n is an example of an escape sequence.
Line 8 prints the value of the variable num (1) embedded in the phrase. The %d instructs the computer
where and in what form to print the value. %d is a type specifier used to specify the output format for
integer numbers.
Line 9 has the same effect as line 7.
Line11 indicates the value to be returned by the function main( ) when it is executed.
7
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
By default any function used in a C program returns an integer value (when it is called to execute).
Therefore, line 2 could also be written int main( ). If the int keyword is omitted, still an integer is returned.
Then, why return (0); ? Since all functions are subordinate to main( ), the function does not return any
value.
Note
i) Since the main function does not return any value, line 3 can alternatively be written as : void
main( ) – void means valueless. In this case, the statement return 0; is not necessary.
ii) While omitting the keyword int to imply the return type of the main( ) function does not disqualify
the fact that an integer is returned (since int is default), you should explicitly write it in other
functions, especially if another value other than zero is to be returned by the function.
Comments
Comments are non – executable program statements meant to enhance program readability and allow
easier program maintenance, i.e. they document the program.
They can be used in the same line as the material they explain (see lines 4 and 5 in sample program).
A long comment can be put on its own line or even spread on more than one line.
Comments are however optional in a program. The need to use too many comments can be avoided by
good programming practices such as use of sensible variable names, indenting program statements, and
good logic design. Everything between the opening /* and closing */ is ignored by the compiler.
Declaration statements
In C, all variables must be declared before they are used. Variable declarations ensure that appropriate
memory space is reserved for the variables, depending on the data types of the variables. Line 4 is a
declaration for an integer variable called num.
Escape sequences
Escape sequences (also called back slash codes) are character combinations that begin with a backslash
symbol (\) used to format output and represent difficult-to-type characters.
One of the most important escape sequences is \n, which is often referred to as the new line character.
8
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
\b backspace
\f form feed
\n new line
\v vertical tab
\t horizontal tab
\\ back slash ( \ )
\’ Single quote (‘)
\” Double quote (“ ”)
\0 null
\? Question mark (?)
Example
The program below displays the following output on the screen.
#include<stdio.h>
main()
{
printf(“This is line one \n”);
printf(“This is line two \n”);
printf(“This is line three”);
return 0;
}
Example
The program below sounds the bell.
#include<stdio.h>
main()
{
printf(“\a”);
return 0;
}
Remember that the escape sequences are character constants. Therefore to assign one to a character
variable, you must enclose the escape sequence within single quotes, as shown in this fragment.
char ch;
ch = ‘\t ’ /*assign ch the tab character */
Syntax errors
They result from the incorrect use of the rules of programming. The compiler detects such errors as soon as
you start compiling. A program that has syntax errors can produce no results. You should look for the error
in the line suggested by the compiler.
Syntax errors include;
9
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Missing semi colon at the end of a statement e.g. Area = Base * Length
Use of an undeclared variable in an expression
Illegal declaration e.g. int x, int y, int z;
Use of a keyword in uppercase e.g. FLOAT, WHILE
Misspelling keywords e.g. init instead of int
Note
The compiler may suggest that other program line statements have errors when they may not. This will be
the case when a syntax error in one line affects directly the execution of other statements, for example
multiple use of an undeclared variable.
Declaring the variable will remove all the errors in the other statements.
Logic Errors
These occur from the incorrect use of control structures, incorrect calculation, or omission of a procedure.
Examples include: An indefinite loop in a program, generation of negative values instead of positive
values. The compiler will not detect such errors since it has no way of knowing your intentions. The
programmer must dry run the program so that he/she can compare the program’s results with already
known results.
Semantic errors
They are caused by illegal expressions that the computer cannot make meaning of.
Usually no results will come out of them and the programmer will find it difficult to debug such errors.
Examples include a data overflow caused by an attempt to assign a value to a field or memory space
smaller than the value it requires, division by zero, etc.
Revision Exercise
1. Outline the logical stages of C programs’ development.
2. From the following program, suggest the syntax and logical errors that may have been made.The
program is supposed to find the square and cube of 5, then output 5, its square and cube.
#include<stdio.h>
main()
{
int, int n2, n3;
n = 5;
n2 = n *n
n3 = n2 * n2;
printf(“ n = %d, n squared = %d, n cubed = %d \ n”, n, n2, n3);
return 0;
10
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
}
3. Give the meaning of the following, with examples
i) Preprocessor command
ii) Keyword
iii) Escape sequence
iv) Comment
v) Linking
vi) Executable file
4. C is both ‘portable’ and ‘efficient’. Explain.
5. C is a ‘case sensitive’ language. Explain.
6. The use of comments in C programs is generally considered to be good programming practice.
Why?
Variables
A variable is a memory location whose value can change during program execution. In C, a variable must
be declared before it can be used. Variables can be declared at the start of any block of code.
A declaration begins with the data type, followed by the name of one or more variables.
That is:
datatype variable; or
datatype variable1,variable2,….variablen; (where there are n variables)
For example:
int high, low, results[20];
Declarations can be spread out, allowing space for an explanatory comment. That is:
Variables can also be initialised when they are declared. This is done by adding an equals sign and the
required value after the declaration.
int high = 250; /* Maximum Temperature */
int low = - 40; /* Minimum Temperature */
int results[20]; /* Series of temperature readings */
Variable names
Every variable has a name and a value. The name identifies the variable and the value stores data. There is
a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the
name can consist of letters, numbers and underscore characters.
C recognizes upper and lower case characters as being different (C is case- sensitive).
Finally, you cannot use any of C's keywords like main, while, switch etc as variable names.
It is conventional to avoid the use of capital letters in variable names. These are used for names of
constants. The rules governing variable names also apply to the names of functions.
11
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Types of variables
There are two places where variables are declared: inside a function or outside all functions.
Global variables
Variables declared outside all functions are called global variables and they may be accessed by any
function in your program. Global variables exist the entire time your program is executing.
Local variables
Variables declared inside a function are called local variables. A local variable is known to and may be
accessed by only the function in which it is declared. You need to be aware of two important points about
local variables.
i) The local variables in one function have no relationship to the local variables in another function.
That is, if a variable called count is declared in one function, another variable called count may
also be declared in a second function – the two variables are completely separate from and
unrelated to one another.
ii) Local variables are created when a function is called, and they are destroyed when the function is
exited. Therefore local variables do not maintain their values between function calls.
Integer variables may hold signed whole numbers (numbers with no fractional part).
Typically, an integer variable may hold values in the range –32,768 to 32,767 and are 2 bytes long.
12
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Double-type variables typically occupy 8 bytes (64 bits). Has accuracy up to 15 digits.
In order to display the correct values using printf() function conversion specifiers/ format characters/
format specifiers should be used. They are used to instruct the compiler about the type of numbers
appearing in the program, which in turn determines the suitable memory storage locations. In this case, the
%d, means that an integer is to be output in decimal format. The value to be displayed is to be found in the
second argument. This value is then output at the position at which the format specifier is found on the
string. If you want to specify a character value, the format specifier is %c. To specify a floating point value,
use %f. The %f works for both float and double. Keep in mind that the values matched with the format
specifier need not be constants (such as 99 in the printf statement above). They may be variables too.
Examples
i) The program shown below illustrates the above concepts. First, it declares a variable called num.
Second, it assigns this variable the value 100. Finally, it uses printf( ) to display the value is 100
on the screen. Examine it closely.
#include<stdio.h>
main()
{
int num;
num = 100;
printf(“ The value is %d “, num);
return 0;
}
ii) This program creates variables of types char, float, and double assigns each a value and outputs
these values to the screen.
#include<stdio.h>
main()
13
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
{
char ch;
float f;
double d;
ch = ‘X’;
f = 100.123;
d = 123.009;
printf(“ ch is %c “, ch);
printf(“ f is %f “, f);
printf(“ d is %f “, d);
return 0;
}
Exercise
Enter, compile, and run the two programs above.
Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer
%e Read a floating point number
%f Read a floating point number
%lf Read a double
%s Read a string
%u Read an unsigned integer
Examples
i) This program asks you to input an integer and a floating-point number and displays the value.
#include<stdio.h>
main()
{
int num;
float f;
printf(“ \nEnter an integer: “);
scanf( “%d “, &num);
14
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Storage classes
C storage classes determine how a variable is stored. The storage class specifiers are
auto
extern
register
static
auto
auto is the default storage class for local variables. The example below defines two variables with the same
storage class. auto can only be used within functions, i.e. local variables.
{
int Count;
auto int Month;
}
extern
As the size of a program grows, it takes longer to compile. C allows you to break down your program into
two or more files or functions. You can separately compile these files and then link them together. In
general, global data may only be declared once.
Because global data may need to be accessed by two or more functions that form the program, there must
be a way of informing the compiler about the global data used by the program.
Consider the following;
File 1
#include<stdio.h>
int count;
15
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
void f1 (void);
main()
{
int i;
f1 ( ); /* Set count’s value */
for( i =0; i <count; i++)
printf(“%d”);
return 0;
}
File 2
#include<stdlib.h>
void f1(void)
{
count = rand ( ); /* Generates a random number */
}
If you try to compile File 2, an error will be reported because count is not defined.
However, you can change File 2 as follows:
#include<stdlib.h>
int count;
void f1(void)
{
count = rand (); /* Generates a random number */
}
But there is still a problem, If you declare count a second time, the linker will report a duplicate-symbol
error, which means that count is defined twice, and the linker doesn’t know which to use. The solution to
this problem is C’s extern specifier. By placing extern in front of count’s declaration in File 2, you are
telling the compiler that count is an integer declared elsewhere. In other words, using extern informs the
compiler about the existence and type of the variable it precedes but does not cause storage for that
variable to be allocated. The correct version for File 2 is:
#include<stdlib.h>
extern int count;
void f1(void)
{
count = rand ( ); /* Generates a random number */
}
Note: stdlib.h is a header file that contains certain standard library functions. These functions include:
rand() – function is one of them and is used to generate a random number between
abort() – to abort a program,
abs() – to get the absolute value ,
malloc() for dynamic memory allocation ,
free() to free memory allocated with malloc(),
qsort()to sort an array,
realloc() to reallocate memory, et al.
register
register is used to define local variables that should be stored in a register instead of Random Access
Memory (RAM). For example: register int Miles; register should only be used for variables that require
quick access - such as counters.
16
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It
means that it might be stored in a register - depending on hardware and implementation restrictions.
static
The static modifier causes the contents of a local variable to be preserved between function calls. Also,
unlike normal local variables, which are initialized each time a function is entered a static variable is
initialized only once. For example, take a look at the following program:
#include<stdio.h>
void f(void);
main()
{
int i;
for (i =0; i < 10; i ++)
f( );
return 0;
}
void f (void)
{
static int count = 0;
count ++;
printf(“Count is %d \n”, count);
}
which displays the following output.
visibly from above, count retains its value between function calls.
Constants
A constant is a value that does not change during program execution. In other words, constants are fixed
values that may not be altered by the program.
Integer constants are specified as numbers without fractional components. For example –10, 1000.
Floating - point constants require the use of the decimal point followed by the number’s fractional
component. For example, 11.123 is a floating point constant. C allows you to use scientific notation for
floating point numbers. Constants using scientific notation must follow this general form:
17
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
ch = “A’;
ch = 65;
Types of constants
Constants can be used in C expressions as:
Direct constants
Symbolic constants
Direct constants
Here the constant value is inserted in the expression, as it should typically be.
For example:
Area = 3.14 * Radius * Radius;
The value 3.14 is used directly to represent the value of PI which never requires changes in the
computation of the area of a circle
Symbolic constant
This involves the use of another C preprocessor, #define.
For example, #define SIZE 10
A symbolic constant is an identifier that is replaced with replacement text by the C preprocessor before the
program is compiled. For example, all occurrences of the symbolic constant SIZE are replaced with the
replacement text 10.
This process is generally referred to as macro substitution. The general form of the
#define statement is;
#define macro-name string
Notice that this line does not end in a semi colon. Each time the macro - name is encountered in the
program, the associated string is substituted for it. For example, consider the following program.
Example: Area of a circle
#include<stdio.h>
#define PI 3.14
main()
{
float radius, area;
printf(“Enter the radius of the circle \n”);
scanf(“%f”, &radius);
area = PI * radius * radius; /* PI is a symbolic constant */
printf(“Area is %.2f cm squared “,area);
return 0;
}
At the time of the substitution, the text such as 3.14 is simply a string of characters composed of 3, ., 1 and
4. The preprocessor does not convert a number into any sort of internal format. This is left to the compiler.
The macro name can be any valid C identifier. Although macro names can appear in either uppercase or
lowercase letters, most programmers have adopted the convention of using uppercase for macro names to
distinguish them from variable names. This makes it easy for anyone reading your program to know when
a macro name is being used.
Macro substitutions are useful in that they make it easier to maintain programs. For example, if you know
that a value, such as array size, is going to be used in several places in your program, it is better to create a
macro for this value. Then, if you ever need to change this value, you simply change the macro definition.
All references will be automatically changed when the program is recompiled.
Revision Exercise
1. Discuss four fundamental data types supported by C, stating how each type is stored in memory.
18
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
CHAPTER 3-OPERATORS
Introduction
How does a C programmer tell a program to perform a calculation, compare values and so on. This requires
one to know the symbols associated with these tasks, for example ‘+’ for addition, ‘>’ for checking whether
one value is greater than another value, ‘=’ for assignment of a value to a variable etc.
1. Arithmetic operators
There are five arithmetic operators in C.
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division, remainder after integer division
Note:
19
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
i. The operands acted upon by arithmetic operators must represent numeric values, that is
operands may be integers, floating point quantities or characters (since character constants
represent integer values).
ii. The % (modulo division operator) requires that both operands be integers.
Thus;
5%3
int x = 8;
int y = 6 ; x % y are valid while;
8.5 % 2.0 and
float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.
iii. Division of one integer quantity by another is known as an integer division. If the quotient
(result of division) has a decimal part, it is truncated.
iv. Dividing a floating point number with another floating point number, or a floating point number
with an integer results to a floating point quotient . If one or both operands represent negative
values, then the addition, subtraction, multiplication, and division operators will result in values
whose signs are determined by their usual rules of algebra. Thus if a b, and c are 11, -3 and -11
respectively, then
a+b=8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3
20
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
( i + c) - ( 2 * f / 5)
(‘w” has ASCII decimal value of 119)
Type Conversion
You can mix the types of values in your arithmetic expressions. char types will be treated as int. Otherwise
where types of different size are involved, the result will usually be of the larger size, so a float and a
double would produce a double result.
Where integer and real types meet, the result will be a double.
There is usually no trouble in assigning a value to a variable of different type. The value will be preserved
as expected except where:
The variable is too small to hold the value. In this case it will be corrupted (this is bad).
The variable is an integer type and is being assigned a real value. The value is rounded down. This
is often done deliberately by the programmer.
Values passed as function arguments must be of the correct type. The function has no way of
determining the type passed to it, so automatic conversion cannot take place.
This can lead to corrupt results. The solution is to use a method called casting which temporarily disguises
a value as a different type.
For example, the function sqrt finds the square root of a double.
int i = 256;
int root;
root = sqrt( (double) i);
The cast is made by putting the bracketed name of the required type just before the value, (double) in this
example. The result of sqrt( (double) i) is also a double, but this is automatically converted to an int on
assignment to root.
Operator precedence
The order of executing the various operations makes a significant difference in the result. C assigns each
operator a precedence level. The rules are;
i. Multiplication and division have a higher precedence than addition and subtraction, so they are
performed first.
ii. If operators of equal precedence; (*, /), (+, -) share an operand, they are executed in the order in
which they occur in the statement. For most operators, the order (associativity) is from left to
right with the exception of the assignment ( = ) operator.
21
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Note that it is possible for the programmer to set his or her own order of evaluation by putting, say,
parenthesis. Whatever is enclosed in parenthesis is evaluated first.
What is the result of the above expression written as:
(25+ 60.0 * n) / SCALE?
Examples of assignment:
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;
22
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Note
i. You cannot assign a variable to a constant such as 3 = a ;
ii. The assignment operator = and equality operator (= =) are distinctively different. The = operator
assigns a value to an identifier. The equality operator (= =) tests whether two expressions have
the same value.
iii. Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a and b.
iv. Assignment can be combined with +, -, /, *, and %
3. Relational operators
There are four relational operators in C.
< Less than
<= Less than or equal to
> Greater than
> = Greater than or equal to
Closely associated with the above are two equality operators;
· = = Equal to
· ! = Not equal to
The above six operators form logical expressions.
A logical expression represents conditions that are either true (represented by integer 1) or false
(represented by 0).
Example
Consider a, b, c to be integers with values 1, 2, 3 respectively. Note their results with relational operators
below.
Expression Result
a<b 1 (true)
(a+ b) > = c 1 (true)
(b + c) > (a+5) 0 (false)
c:=3 0 (false)
b==2 1 (true)
4. Logical operators
&& Logical AND
|| Logical OR
! NOT
The three operators act upon operands that are themselves logical expressions to produce more complex
conditions that are either true or false.
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is a
character that represents the character ‘w’, then;
(i > = = 6 ) && ( C = = ‘w’ ) is 1 (true)
( C’ > = 6 ) || (C = 119 ) is 1 (true)
(f < 11 ) && (i > 100) is 0 (false)
(C! = ‘ p’) || ((i + f) < = 10 ) is 1 (true)
23
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
6. Unary operators
These are operators that act on a singe operand to produce a value. The operators may precede the operand
or are after an operand.
Examples
(i) Unary minus e.g. - 700 or –x
(ii) Incrementation operator e.g. c++
(iii) Decrementation operator e.g. f - -
(iv) sizeof operator e.g. sizeof( float)
Revision Exercise
1. Describe with examples, four relational operators.
2. What is ‘operator precedence’? Give the relative precedence of arithmetic operators.
3. Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3 and c = - 5, x, y, z are
floating point variables with values x =8.8, y = 3.5, z = -5.2.
24
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.
25
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)
lOMoARcPSD|48268036
26
Downloaded by Meshack Kibet (meshackkibet8078@gmail.com)