0% found this document useful (0 votes)
3 views18 pages

CMP201 - Lecture Notes

The document provides an overview of computer programming, detailing the functions of computers, problem-solving strategies, algorithms, and programming languages, particularly Java. It explains the stages of programming, including defining problems, developing algorithms, coding, debugging, and testing. Additionally, it covers Java's features, such as its simplicity, object-orientation, and portability, as well as basic programming concepts like data types, variable declaration, and arithmetic operators.

Uploaded by

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

CMP201 - Lecture Notes

The document provides an overview of computer programming, detailing the functions of computers, problem-solving strategies, algorithms, and programming languages, particularly Java. It explains the stages of programming, including defining problems, developing algorithms, coding, debugging, and testing. Additionally, it covers Java's features, such as its simplicity, object-orientation, and portability, as well as basic programming concepts like data types, variable declaration, and arithmetic operators.

Uploaded by

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

INTRODUCTION

A computer is a device capable of performing computations and making logical


decisions at speeds millions (even billions) of times faster than human beings. For
example, many of today’s computers can perform a billion additions per second. A
person operating a desk calculator could spend an entire lifetime performing
calculations and still not complete as many calculations as a powerful computer
can perform in one second.
Computers process data under the control of sets of instructions called computer
programs. These programs guide the computer through orderly sets of actions
specified by people called computer programmers. The programs that run on a
computer are referred to as software.

PROBLEM SOLVING

Solving any given problem means that we know the way or the method to follow
manually from start to finish. Having established the steps to follow to solve a
problem, the steps can easily be coded in a programming language so that the
computer can implement the actions. If we do not know how to solve a problem
manually, the computer will not be of any help to us.
The strategy for solving a programming problem uses the following stages:
1. Defining the problem: Unless you are solving some trivial problems, some
preparatory thinking must precede the action of coding. You must state
clearly what needs to be done before you begin to do it. This step is the most
important in programming. Defining the problem is divided into three
separate components:
i. Identify the inputs.
ii. Identify the outputs.
iii. The processing steps to produce required outputs.
2. Developing an algorithm: An algorithm is a precise and ordered outline of
the proposed solution. This involves specifying the required data types and
the logical sequences of steps that solve the problem.
3. Coding and Debugging: it is only at this stage in programming that we start
coding the solution to the problem. Unlike the previous steps, this should be
an easy step if the algorithm has been developed in sufficient detail. Each
program as it is coded, needs to be debugged to remove errors.
4. Testing the program: This step uses a program compiler and programmer-
designed test data to test the code for syntax errors and logical errors.
5. Producing enhanced documentation
6. Maintenance

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 1


ALGORITHMS, PSEUDOCODE, AND FLOWCHART

An Algorithm is a sequence of instructions that solve a problem. An Algorithm


lists the steps involved in accomplishing a task (like a recipe). Algorithms has the
following properties:
1. No ambiguity in any instruction
2. The sequence of instructions is clearly defined.
3. It has finite number of instructions.
The description of the instructions can be written in English like statements called
pseudocode. A Pseudocode is a structured English (formalized and abbreviated to
look like high-level computer language).

A Flowchart is a graphical representation of the sequence of operations in an


information system or program. Program flowcharts show the sequence of
instructions in a single program or subroutine. It also shows the logic of an
algorithm and emphasizes individual steps with their interconnections. e.g. control
flow from one action to the next
Note: Different symbols are used to draw each type of flowchart.

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 2


Example 1: Write an algorithm and draw a flowchart that will read the two sides of
a rectangle and calculate its area.

Pseudocode
 Input the Length (L) and Breath (B) of a rectangle.
 Calculate the area (A) by multiplying L with B
 Print A

Algorithm
Step 1: Input L,B
Step 2: A=L x B
Step 3: Print A

Flowchart
CMP201 Computer Programming I, Department of Computer Science, UDUS Page 3
Example 2: Write an algorithm and draw a flowchart that will calculate the roots of
a quadratic equation. Hint: d = sqrt ( ), and the roots are: x1
= (–b + d)/2a and x2 = (–b – d)/2a

Pseudocode:
 Input the coefficients (a, b, c) of the quadratic equation
 Calculate d
 Calculate x1
 Calculate x2
 Print x1 and x2

Algorithm:
Step 1: Input a, b, c
Step 2: d = sqrt ( )
Step 3: x1 = (–b + d) / (2 x a)
Step 4: x2 = (–b – d) / (2 x a)
Step 5: Print x1, x2

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 4


Flowchart

COMPUTER PROGRAMMING

The functions of a computer system are controlled by computer programs. A


computer program is a clear, step-by-step, finite set of instructions. A computer
program must be clear so that only one meaning can be derived from it. The
process of writing computer programs is known as computer programming. A
computer program is written by a computer programmer in a computer language
called a programming language.

PROGRAMMING LANGUAGES

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 5


To communicate between any two people they must either both understand a
common language or there must be a third person who understands the language of
the two people involved. This is exactly the situation between a computer and a
user.
All digital computers are designed to understand only one language called Machine
Language. This language consists of only two symbols 0’s and 1’s. Thus words
and sentences are constructed to consist of only those two symbols. This makes
machine language very difficult to understand and use by computer programmers
as it is easy to make mistakes.
Human beings on the other hand understand Natural Languages such as English,
French, Hausa and Yoruba. These languages are easier to use, but also have their
problem of ambiguity. For example consider the English sentence “I am coming”.
The sentence could mean different things depending on the situation and even
though human beings can deal with this situation, computers are not able to cope
because of their limited intelligence.
To achieve a compromise, programming languages known as High Level
Languages (HLL) were developed. These were developed to be as close as
possible to Natural Languages, but at the same time very specific to suit the nature
of computers. The first attempt to develop a HLL was Assembly Language. This
consists of symbolic words called mnemonics (e.g. load, add, store, move).
However, assembly language was not adequate enough hence other higher
programming languages were developed to allow programs to be written in terms
of mathematical expressions. Some of these languages are BASIC, FORTRAN,
COBOL, C++, JAVA, and VISUAL BASIC.
However, since computers understand only machine language, programs called
Language Translators are needed to translate from High Level Language to
Machine Language. Examples of language translators include Assemblers,
Compilers and Interpreters. A Java compiler for example understands both
machine language and the Java high level language. Thus when a programmer
writes a program using Java, it is submitted to the Java compiler to produce an
intermediate code called bytecode. The bytecode is then interpreted by the Java
Virtual Machine into machine code, which the computer can understand.

THE JAVA PROGRAMMING LANGUAGE

Java is today one of the most popular programming languages. Some of the
reasons why Java is popular include:
1. Simplicity: Compared to many other languages, Java is simple to learn and
use

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 6


2. Object-Orientation: Java is an object-oriented language and therefore has a
lot of benefits of object-oriented programming.
3. Secure: The Java system controls what parts of your computer a program
can access thus securing against viruses
4. Compatibility: A Java program will run identically on every platform with
the help of the JVM. Dissimilar to numerous other programming dialects
including C and C++, when Java is aggregated, it is not converted into a
form, which is particular to any machine. Instead, it is converted into a
machine-independent byte code. This byte code is conveyed over the web
and deciphered by Virtual Machines or JVM on whichever stage it is
generally run.
5. Independent of Machine Architecture: Java compiler produces an object file
format, which is independent of the architecture of the machine. The
assembled code can be executed on numerous processors, with the single
requirement that they must all have Java runtime framework.
6. Java is designed such that it can download programs over the Internet and
execute them.
7. Portability: The fact that Java code is machine and platform independent
makes it extremely compact. Compiler in Java is composed in ANSI C with
a clean conveyability limit, which is a POSIX subset.
8. Robustness: Java tries to kill circumstances, which can lead to potential
system failures, by stressing chiefly on runtime checking and compile time
checking.
9. Support for Multithreaded Applications: With Java’s multithreaded feature,
it is conceivable to compose programs that can do numerous assignments at
the same time. This configuration gimmick permits designers to build easily
running intelligent applications.
10.Interpreted Code: Java byte code is interpreted on the fly to local machine.
The advancement methodology is quicker and more expository since the
interfacing is an incremental and lightweight process.

PROGRAM CONSTRUCTION TOOLS

To write (edit) and test (debug) programs, you need two basic tools mainly a text
editor and a compiler. A text editor is a program that allows a user to create and
modify programs. Examples of editors include Notepad, Textpad, Jcreator, Jblue
and Netbeans. A compiler translates the program (source code) into machine code
and also helps to debug the program by pointing out the errors that may exist. An
example of a compiler is the JDK6.0 compiler for Java.

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 7


JAVA IDENTIFIER

To be able to refer to entities stored in computer memory, Java allows the


programmer to attach names to portions of memory. The technical name for these
names is Identifiers. In Java, an identifier can be any combination of letters and
numbers but must conform to the following three rules:
1. All identifiers ought to start with a letter (beginning to end or a to z),
underscore
(_) or special character ($).
2. After the first character, identifiers can have any mix of characters.
3. You cannot use a keyword (Java reserve words) as an identifier.
4. Most significantly, identifiers are case sensitive. So, Sample is not same as
sample.
There are also some other rules which are followed but are not compulsory:
1. All identifiers begin with a lowercase letter except it is the name of a class
2. For compound words, the first word begins with lower case while
subsequent words begin with an upper-case letter e.g. classNumber,
myProgram, areaOfTriangle

Examples of valid identifiers include Radius, myJob, a, $salary, age, __1_value


and _value.

JAVA MODIFIERS

Like is the case with any programming language, it is conceivable to alter classes
and systems by utilizing modifiers. There are two classifications of modifiers:

1. Access Modifiers: public, default, protected and private.


2. Non-access Modifiers: strictfp, final and abstract

PRIMITIVE DATA TYPES

Data types represent how identifiers are stored in the computer or in lay terms, the
amount of space reserved for an identifier in memory. Java has eight primitive data
types as follows:

Type Size Range


byte I byte -128 to 127
short 2 bytes -32,748 to 32,767
CMP201 Computer Programming I, Department of Computer Science, UDUS Page 8
int 4 bytes -2 billion to 2 billion
long 8 bytes -10E18 to 10E18
float 4 bytes -3.4E38 to 3.4E38
double 8 bytes -1.7E308 to 1.7E308
char 2 bytes A single character
boolea 1 byte True or false
n

VARIABLE DECLARATION

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 primitive types. The following examples illustrate how a variable is declared as
a data type, and how it stores a value.
int counter;
int numberOfStudents = 60;
char gender = ‘m’;
boolean pass = true;

MEMORY CONCEPTS

Variable names such as numberOfStudents and counter actually correspond to


locations in the computers memory. Every variable has a name, a type, a size and a
value. When we write int counter = 5; the value 5 is placed into a memory location
to which the name counter has been assigned by the compiler. Whenever a value is
placed in a memory location, the value replaces the previous value in that location.
The previous value is lost. For example if later in the program we write counter =
10; the value 5 will be replaced by 10.

ARITHMETIC OPERATORS

These are the operators used for performing arithmetic operations in a Java
program. A simple arithmetic expression has the form:

OP1 operator OP2

OP1 and OP2 are called the operands which are going to be operated on. The
following table lists the various operators and their functions:
CMP201 Computer Programming I, Department of Computer Science, UDUS Page 9
Operato Function
r
+ 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

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:


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

THE MATH CLASS

Obviously the arithmetic operators discussed above do not solve all possible
mathematical problems. However, many mathematical functions are included in
the Math class of the Java library, which is available for the programmers use.
Some of the functions include:

Function Action
sqrt(X) Returns the square root of X
abs(X) Returns the absolute value of X
cos(X), sin(X), tan(X) Returns the trig values of an angle
exp(X) Returns the exponential number e to the power of X

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 10


log(X) Returns the natural logarithm of X
pow(X, Y) Returns X to the power of Y

The syntax of using any of these functions is Math.FunctionName(Variable). An


example of this is given:
1. To calculate the square of the number X, you write Math.pow(X, 2)
2. Math.abs(X – Y) returns the absolute value of X minus Y

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

Exercise: 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

SHORT HAND ASSIGNMENT OPERATORS

Java provides a number of shorthand assignment operators:

Short form Equivalent


OP1 += OP2 OP1 = OP1 + OP2
OP1 -= OP2 OP1 = OP1 – OP2
OP1 *= OP2 OP1 = OP1 * OP2
OP1 /= OP2 OP1 = OP1 / OP2
OP1 %= OP2 OP1 = OP1 % OP2

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 11


Example: a += 5; //equivalent to a = a + 5;

INCREMENT AND DECREMENT OPERATORS

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;

Java provides operators that make these operations shorter.

Operato Use Description


r
++ OP++ Increments OP by 1
-- OP-- Decreases OP by 1

Example: int y = 20;


y++; // the new value of y is 21

DECISION MAKING: EQUALITY AND RELATIONAL OPERATORS

The table below summarizes the equality and relational operators used in Java:

Operator Sample Java condition Meaning


== X == Y X is equal to Y
!= X != Y X is not equal to Y
> X>Y X is greater than Y
< X<Y X is less than Y
>= X >= Y X is greater than or equal to Y
<= X <= Y X is less than or equal to Y
WRITING ALGEBRAIC EXPRESSIONS IN JAVA

When writing algebraic expressions in Java, all operators must be explicit. For
fractions, the numerator and denominator should be placed in parenthesis.

Example: Write the following algebraic expressions in Java


1. Z = 4X + Y/X2 – 2Y
2. Z = √X + Y2
CMP201 Computer Programming I, Department of Computer Science, UDUS Page 12
Solution: 1. Z = (4*X + Y)/ Math.pow(X,2) – 2*Y
2. Z = Math.sqrt(X + Math.pow(Y,2)

STRUCTURE OF SIMPLE JAVA PROGRAMS

The following figure shows a simplified structure of Java programs.

public class ClassName


{
public static void main (String[] args)
{
Statement 1;
Statement 2;
Statement n;
}
}

Every Java program is placed inside a container called a class. All the program
code is placed within the boundaries of the class starting from the opening brace
‘{‘, and closed by the last brace ‘}’. The programmer will give the program a name
called the ‘class name’, which can be any valid identifier chosen.
Inside the class, there is another unit called the main method. It is inside the main
method that the programmer writes the instructions that make up the program.
These instructions are written line by line as statements ended by semicolon ‘;’.
Note that even the main method has opening and closing curly brackets. These
curly brackets are called delimiters and are very important in Java. They cannot be
omitted or replaced with any other kind of bracket.
After editing the program code, it must be saved in a file that has the same name as
the class. For example if the class name is myProgram, then the file will be called
myProgram.java.

SOURCE PROGRAM: EXAMPLE

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 13


public class WelcomeMessage
{
public static void main (String[] args)
{
System.out.println(“Welcome to programming in Java”);
System.out.println(“Have a nice time”);
}
}

The class name of the program above is WelcomeMessage, which implies it will
be stored in a file named WelcomeMessage.java. Inside the main method, there are
two ‘print’ statements, which will print the following on the computer screen when
the program is executed.

Welcome to programming in Java


Have a nice time

Java provides the programmer with some useful statements like the ‘print
statement’ to help perform some tasks automatically.

The Print statements

1. System.out.print: This first print statement prints the characters placed


within the quotation marks and leaves the cursor on the same line.
2. System.out.println: This print statement prints the characters placed within
the quotation marks and moves the cursor to the next line.

Example: How will the output of the following statements appear on the screen?
1. System.out.println(“Welcome”);
System.out.println(“Hello”);
2. System.out.print(“Welcome”);
System.out.print(“Hello”);
3. System.out.print(“Welcome “);
System.out.print(“Hello”);

Answer: 1. Welcome
Hello
2. WelcomeHello
3. Welcome Hello

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 14


However, there exist some special characters called “Escape Sequence” that can be
used to change how the output should appear. Some of them include:
Escape sequence Description
\n Newline. Position the cursor on a new line
\t Horizontal tab. Move the screen cursor to the next tab stop
\\ Backslash. Used to print a backslash character
\” Double quote. Used to print a double quote character

Example: System.out.print(“Welcome\nTo\nProgramming\nIn\nJava”);
The statement above will print the following:
Welcome
To
Programming
In
Java
Example: System.out.print(“\”How old are you?\””);
The statement above will print the following:
“How old are you?”

SIMPLE JAVA PROGRAMS

Example 1: Write a program that will calculate the area of a rectangle.

Solution

The first step obviously is to define the problem. We need to know how the area of
a rectangle is calculated i.e. the formula, which is given by lb where l is the length
of the rectangle and b is the breadth.
Hence a possible algorithm for this problem could be:
1. Obtain the values of length l and breadth b and store them in the computer
2. Provide a space in memory where the area will be stored
3. Calculate the area (lb) and store it
4. Display the result

The Java equivalent of the algorithm is:

public class AreaOfRectangle{


public static void main (String[] args) {
CMP201 Computer Programming I, Department of Computer Science, UDUS Page 15
double length = 6.5;
double breadth = 4;
double area;
area = length * breadth;
System.out.println(area);
}
}

Note: The print statement in the program above does not use quotation marks
inside the brackets. In fact whenever the content of a variable that is already stored
in the memory needs to be printed, quotation marks are not necessary. The output
of the above program will be 26.0
If we change the print statement above to system.out.println(“The area is “ + area);
the output of the program will be The area is 26.0. This is called concatenation and
it involves using the ‘+’ sign to combine different values for display.

Example 2: Write a program that will calculate the average of two numbers
Solution
The algorithm is given below:
1. Obtain the values of the three numbers and store in memory
2. Provide a space in memory where the average will be stored
3. Calculate the average (add the three numbers and divide by 3) and store it
4. Display the result

The Java equivalent of the algorithm is:

public class Average{


public static void main (String[] args) {
int number1 = 10;
int number2 = 4;
int number3 = 16;
double average;
average = (number1 + number2 + number3)/3;
System.out.println(“The average is “ + average);
}
}

Example 3: Write a program to calculate the area of a triangle given the length of
the sides:, a = 3, b = 4, c = 5. Use the following formula:
Area = √(s(s – a)(s – b)(s – c)), where s = (a + b + c)/2

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 16


Algorithm
1. Store the values of a, b and c in memory
2. Provide 2 spaces in memory where the values of s and area will be stored
3. Calculate the value of s and store it
4. Calculate the area and store it
5. Display the area

public class Average{


public static void main (String[] args) {
int a = 3;
int b = 4;
int c = 5;
double s, area;
s = (a + b + c)/2;
area = Math.sqrt(s*(s – a)*(s – b)*(s – c));
System.out.print(“The area is “ + area);
}
}

READING INPUT FROM THE USER

At this point it is important to learn how to obtain input from the user during
program execution. So far, we have hard coded all the data needed by our
programs. But in most cases, we need to obtain some input from the user while the
program is running.

Example 1: Let us write a program that prints a persons name first by hard coding
the name into the program, and then by obtaining the name from the user.

public class Name {


public static void main (String[] args){
String name = “Fatima”;
System.out.println(“My name is “ + name);
}
}

import java.util.Scanner;
public class Name {
public static void main (String[] args){

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 17


Scanner input = new Scanner(System.in);
String response;
System.out.println(“Please enter your name”);
response = input.next( );
System.out.println(“My name is “ + response);
}
}

Explanation

We introduce the Scanner class, which is used to create an object that can read user
input.

The following statement: Scanner input = new Scanner (System.in); creates the
object input, which can read the user input and store it in the computer memory.
The Scanner class has already been implemented and is part of the classes stored in
the Java library. So to use it in our program, we have to make reference to it by
including the following statement at the beginning of the program import
java.util.Scanner;

The statement: String response indicates that we are going to use the variable name
to store our input, and that the input is going to be a string of characters. After
obtaining the name from the user it will be stored using this variable. The
statement: response = input.next( ); uses the input object we created to read what
the user has input and stores it in the variable name, which we have previously
declared.

CMP201 Computer Programming I, Department of Computer Science, UDUS Page 18

You might also like