First Part CSC 201 Fug Introduction To Programming
First Part CSC 201 Fug Introduction To Programming
INTRODUCTION
You may already have used software, perhaps for word processing or spreadsheets, to solve
problems. Perhaps now you are curious to learn how programmers write software.
A program is a set of step-by-step instructions that directs the computer to do the tasks you
want it to do and produce the results you want. A set of rules that provides a way of telling a
computer what operations to perform is called a programming language. There is not,
however, just one programming language; there are many. In this course and its pre -
requisite you will learn about controlling a computer through the process of programming.
You may even develop interest as a computer scientist and discover that you might want to
become a programmer. An important point before we proceed: You will not be a programmer
when you finish reading this course or even when you finish reading the second course.
Programming proficiency takes practice and training beyond the scope of this course.
However, you will become acquainted with how programmers develop solutions to a variety
of problems.
In general, the programmer's job is to convert problem solutions into instructions for the
computer. That is, the programmer prepares the instructions of a computer program and runs
those instructions on the computer, tests the program to see if it is working properly, and
makes corrections to the program. The programmer also writes a report on the program.
These activities are all done for the purpose of helping a user fill a need, such as paying
employees, billing customers, or admitting students to college. The programming activities
just described could be done, perhaps, as solo activities, but a programmer typically interacts
with a variety of people. For example, if a program is part of a system of several programs,
the programmer coordinates with other programmers to make sure that the programs fit
together well. If you were a programmer, you might also have coordination meetings with
users, managers, systems analysts, and with peers who evaluate your work-just as you
evaluate theirs.
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 1
Defining the Problem
Suppose that, as a programmer, you are contacted because your services are needed. You
meet with users from the client organization to analyze the problem, or you meet with a
systems analyst who outlines the project. Specifically, the task of defining the problem
consists of identifying what it is you know (input-given data), and what it is you want to
obtain (output-the result). Eventually, you produce a written agreement that, among other
things, specifies the kind of input, processing, and output required.
Planning the solution
There are two (2) common ways of planning the solution to a problem which are drawing a
flowchart and writing pseudocode, or possibly both. A flowchart is a pictorial
representation of a step-by-step solution to a problem. It consists of arrows representing the
direction the program takes and boxes and other symbols representing actions. It is a map of
what your program is going to do and how it is going to do it. The American National
Standards Institute (ANSI) has developed a standard set of flowchart symbols. The Figure
below shows the symbols and how they might be used in a simple flowchart of a common
everyday problem that involves preparing a letter for mailing.
The algorithm
1. Read the temperature given in degree Celsius.
2. Convert the temperature in Celsius to Fahrenheit using the formula: F=(C * 5/9) +32
4. End
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 5
Example 3. Let’s consider a problem of writing a simple program that can solve quadratic
equation using general formulae i.e.
Start
Input a, b & c
Compute
D<0 D>0
If D =
0
Compute X = Compute
Print “No solution”
Stop
Figure 2: Flowchart solution of example 1.
Example 4: Consider a problem of designing a program that receives C.A and Exam scores
of the students and determines whether students pass or fail base on their total score. The
total score is calculated as the sum of C.A and Exam scores.
Solution: We design the program by drawing a flowchart and write a pseudo code of the
problem solution as follows:
Flowchart:
START
Input
C.A & Exam
FALSE TRUE
If Total <
40
GRADE<5
0
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 7
STOP
Figure 2: Flowchart solution of example 2.
Pseudocode:
Step 1: Input C.A & Exam
Step 2: Calculate the Total by summing C.A and Exam
Step 3: if Total is below 40
Print “FAIL”
else
Print “PASS”
Exercises
1. Write a pseudo code and draw a flowchart that will receives C.A and Exam scores of
the student and determines the grade of the student.
2. Write an algorithm and draw a flowchart that will read the two sides of a rectangle and
calculate its area
PROGRAMMING LANGUAGES
A Computer can only do what a program can make it to do. To perform a particular, task the
programmer writes a sequence of instructions, called program. Computer is designed to
understand a specified set of instruction code and each of these instructions are stored in the
main memory in the form of binary numbers. Therefore, the symbols of a particular computer
language must be converted to binary set of instructions by the compiler/interpreter.
Computer languages can be classified into three broad categories:
a. Machine language
b. Assembly language
c. High level
Machine Language
The set of instruction codes, whether in binary or in decimal notation, which can be directly
understood by the computer without the help of a translator, is called a machine code or
machine language program. A computer understands information composed only zeros and
ones and hence it uses binary digits for its operation. The computer’s instructions are
therefore coded and stored in memory in the form of 0’s and 1’s. A program written this form
is called machine language program. For example, a typical program instruction to print out a
number on the printer might be:
1011000111110100100
Assembly Language
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 8
Programs can be easily written in alphanumeric symbols instead of 0’s and 1’s. Meaningful
and easily remembered symbols are selected for this purpose. For example, ADD for
addition, SUB for subtraction, CMP for comparison, etc. Such symbols are known as
mnemonics. A program written in mnemonics is called assembly language program. The
writing of programs in assembly language is easier and faster as compared to the writing of
programs in a machine language.
High Level Language
To overcome the difficulties associated with assembly language, high-level language or
procedure-oriented was developed. High-level languages permit programmers to describe
tasks in a form which is problem oriented rather than computer oriented. A programmer can
formulate problems more efficiently in a high-level language.
The instructions written in a high-level language are called statements. The statements more
closely resemble English and mathematics as compared to mnemonics in assembly
languages. Examples of high-level languages are; BASIC, PASCAL, FORTRAN, COBOL,
ALGOL, PL/1, PROLOG, LISP, ADA, C, C++, C#, C, etc.
IDENTIFIER
To be able to refer to entities stored in computer memory, C allows the programmer to attach
names to portions of memory. The technical name for these names is Identifiers. In C, an
identifier can be any combination of letters and numbers but must conform to the following
three rules:
1. It begins with a letter or an underscore (_).
2. It does not contain any space or special symbols like &, (, `
3. It is not a C reserved (key) word
C DATA TYPES
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 9
Data types represent how identifiers are stored in the computer or in lay terms, the amount of
space reserved for an identifier in memory. C data types are divided into two broad groups:
- Numeric
o Integer (byte, short, int, long)
o Floating point (float, double)
- Non Numeric
character
Boolean
Variable: The variable is the basic unit of storage in a C program, it is a memory location
that is use to store value which can be referred to in a program. A variable is defined by the
combination of an identifier/variable name, a type, and an optional initializer. In addition, all
variables have a scope, which defines their visibility, and a life time. An identifier is
normally referred to as a variable when it is used to hold data items to be used in a program.
A variable can be declared to hold a data value of any of the data types.
Variable Declaration
In C, all variables must be declared before they can be used. A declaration provides the
compiler with information about how many bytes in the memory should be allocated for that
variable and how this variable should be interpreted. The basic form of a variable declaration
is shown below:
A variable can be declared and initialize at the same time by specifying an equal sign and a
value as follows:
Note: Keep in mind that the initialization expression must result in a value of the same (or
compatible) type as that specified for the variable.
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 10
We can also declare more than one variable of the same type in the same statement with each
variable name separated by commas as follows:
Here are several examples of variable declarations of various types. Note that some include
an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Variable Types
Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0;). There is no special keyword
designating a variable as local; that determination comes entirely from the location in
which the variable is declared — which is between the opening and closing braces of a
function. As such, local variables are only visible to the functions in which they are
declared; they are not accessible from the rest of the program.
Parameters A parameter is a variable use to pass values to a function which is used in
its computations
CONSTANTS
A constant is an entity whose value does not change in the course of program execution.
Constants are also referred to as literals. Constant can be numeric values or strings. If the
analysis specifies a value is to be stored in memory and will not change while the program is
running then the variable should be declared as a constant, by using the final keyword as
follows:
\’ Single quote
\” Double quote
\\ Backslash
\b Back space
\t tab
\n New line
\r Carriage return on a printer.
iv) Boolean Constant
Boolean constant has two values true and false. Also, the value of true or false
does not convert to any numeric value. E.g flag = true; flag2 = true;
v) String Constant
This is a sequence of characters enclosed between double quotes e.g “Mike”
“Course Participants”, “7688”, “1919”
String surname = “Mudassir”;
String matricNo = “200801102222”
OPERATIONS
All processing within a C program is executed as a mathematical calculation. Thus, the term
“calculations” is broader than simply its mathematics reference.
ARITHMETIC OPERATORS
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 12
These are the operators used for performing arithmetic operations in a C program. A simple
arithmetic expression has the form:
OP1 and OP2 are called the operands which are going to be operated on. The following table
lists the various operators and their functions:
Operator Function
+ Adds OP1 and OP2
- Subtracts OP2 from OP1
* Multiplies OP1 by OP2
/ Divides OP1 by OP2 and discards the remainder
% Gives the remainder when OP1 is divided by OP2
The divide operator can carry out either real or integer division depending on the
values used in the equation. For example, 5/2 will yield the result 2 (and not 2.5). This is
because both values are integer, which forces divide operator to carry out an integer division.
If you wish to carry out a real division then cast one of the value, for example (double)5/2
which will yield 2.5 (and not 2). Applying the double cast temporary converts the first integer
value into a double, thus ruling out integer division.
Casting Primitives
Quite often in programming we assign the value contained in one variable to another variable
for example the following code assigns the value stored into num1 (i.e. 10) to the variable
num2, such that both variables now store 10 as their value.
• int num1=10, num2;
num2 = num1;
Such an assignment was possible because the variables were of the same type. It is not
allowed to directly assign between variables of different types.
For example, the following assignment is not allowed, even though the int type can hold the
value 10.
long longNumber=10;
int intNumber;
intNumber = longNumber;
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 13
To assign between variables of different numeric types we must use casting and to
assign between numeric and string types we must use appropriate conversion methods.
A cast is basically a type command which precedes the source variable and has a temporary
effect of converting the value in the source variable to that specified by the cast
• Format: destinationVariable = (cast) sourceVariable;
• Example: intNumber = (int) longNumber;
In the above example the cast (int) was applied to the long type source variable, so its
contents are temporarily converted to the type integer in order to execute the assignment.
Note if the value being casted is greater than that can be stored in the destination variable
then an Overflow exception will occur. An exception is a runtime error message.
Arithmetic Calculations
In C arithmetical calculations are deemed to be an expression, i.e. equate to a value, and as
such form only part of a statement. In coding an arithmetical calculation, we need to decide
how to use the result of the calculation, for which we have two options
• Store the result for later use, e.g. result = 5 + 2
• Output the result immediately, e.g. printf(5 + 2);
Some examples:
1. 1 / 2 = 0
2. 86/10 = 8
3. 86%10 = 6
4. 2 * 3.2 = 6.4
Arithmetic expressions are evaluated according to the following priority rules:
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 14
1. Highest priority: ( ) Bracketed expressions
2. Second priority: *, /, %
3. Lowest priority: +, -
In addition, all expressions are evaluated from left to right. In the presence of parenthesis,
evaluation starts from the innermost parenthesis
Example: 3 + 7%2 = 3 + 1 = 4
(2 – 5)*5/2 = -3*5/2 = -15/2 = -7
ASSIGNMENT STATEMENT
An assignment statement is a statement that is used to manipulate the value of a variable or to
calculate it using values of other variables. The syntax of an assignment statement is as given
below:
Variable = expression;
The expression on the right is evaluated and the result is assigned to the variable on the left.
The left side must be a variable as illustrated below:
a = 5;
b = a;
b = b + 25;
a + b = 15; // invalid because left side is not a variable
Example: If variable x = 20, and y = 16, how do you interchange the contents of the two
variables?
Ans: A third variable must be introduced as follows:
z = x; // store the contents of x in the third variable
x = y; // copy the value of variable y into x
y = z; // copy the value of variable x into y
Example: a += 5; //equivalent to a = a + 5;
INCREMENT AND DECREMENT OPERATORS
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 15
Increment/decrement operations are very common in programming. It is very common to
come across a situation where you need to increase or decrease a variable by 1 as shown in
the example below
a = a + 1;
counter = counter – 1;
CSC 201 Computer Programming I Lecture Note FEDERAL UNIVERSITY GUSAU Page 16