You are on page 1of 48

College of Science

Department of Computer
Programing Fundamentals (Java)
First Stage

Prepared by:
Ari M.Saeed
2018 - 2019
What is a computer algorithm?
To make a computer do anything, you have to write a computer
program.
To write a computer program, you have to tell the computer, step
by step, exactly what you want it to do.
The computer then "executes" the program, following each step
mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to
choose how it's going to do it.

An algorithm is a list of rules to follow in order to solve a


problem.
Algorithms need to have their steps in the right order.
When you write an algorithm the order of the instructions is
very important.
2
Flowchart
Flowchart: is a diagrammatic representation of an algorithm.

Flowchart are very helpful in writing program and explaining


program to others.

Flowcharts can provide a step-by-step diagram for mapping out


complex situations, such as programming code or
troubleshooting problems with a computer.

Flowchart symbols: Different symbols are used for different


states in flowchart, For example: Input/output and decision
making has different symbols. The table below describes all the
symbols that are used in making flowchart.

3
Flowchart
Symbol Purpose Description

Used to indicate the flow of logic by


Flow line
connecting symbols.

Terminal(Stop/ Used to represent start and end of


Start) flowchart.

Used for input and output operation.


Input / Output The data to be read or displayed are
described inside.
Used for arithmetic operations and
Processing data-manipulations. Instructions are
listed in side the symbol.
Used to represent the operation in
Decision which there are two alternatives, true
and false.

4
Flowchart

5
Examples of flowcharts in programming
• Draw a flowchart to add two numbers entered by user.

6
Examples of flowcharts in programming

7
Examples of flowcharts in programming

Start

Read A, B

No Yes
A<B?

BIG = A BIG = B
SMALL = B Write SMALL = A
BIG,
SMALL

Stop
8
Examples of flowcharts in programming
• Draw flowchart to find the largest among three different numbers
entered by user

9
Pseudocode
Pseudocode is a method of describing computer algorithms
using a combination of natural language and programming
language.
Pseudocode is not actual programming language.
It uses short phrases to write code for programs before you
actually create it in a specific language.

Once you know what the program is about and how it will
function, then you can use pseudocode to create statements to
achieve the required results for your program.

Flowcharts were used to map out programs before writing


one line of code in a language.
10
Examples of Pseudocode
Create a program to add 2 numbers together and then display the
result.
Start Program Start
Enter two numbers, A, B
Add the numbers together Enter A, B
Print Sum
End Program
C =A+ B
Tips: Compare that pseudocode
to an example of a flowchart Print C
to add two numbers.

Stop

11
Convert Pseudocode to Flowchart

Examples:
Start
If student's grade is greater than or equal to 60
Print "passed“
Else
Print "failed"
Endif

Tips:
Convert Pseudocode
To flowchart.

12
Control Flow Statements
The control flow statements in Java allow you to run or skip
blocks of code when special conditions are met.

Without control flow statements, the interpreter executes


these statements in the order they appear in the file from left
to right, top to bottom.

This section describes:


• The decision-making statements (if-then, if-then-else,
switch).
• The looping statements (for, while, do-while).
• The branching statements (break, continue, return).

13
if-then Statement

The if statement is a fundamental control statement that


allows Java to make decisions and execute statements
conditionally.
It checks boolean condition: true or false

if(condition){

//code to be executed 
 

14
if-then Statement
It tells your program to execute a certain section of code only
if a particular test evaluates to true.

For example:

class Ifstatement{
public static void main(String[] args){
int Grade = 67;
if(Grade >= 60){
System.out.print("Passed");
}
}
}
15
if-then-else Statement
The if-then-else statement provides a secondary path of
execution when an "if" clause evaluates to false.

if(Boolean_expression) {
// Executes when the Boolean expression is true
}
else {
// Executes when the Boolean expression is false
}

16
if-then-else Statement
For example:

int Grade=35;
if(Grade >= 50){
System.out.print("Passed");
}else{
System.out.print("Failed");
}

17
Switch Statement
• The body of a switch statement is known as a switch block.
• A statement in the switch block can be labeled with one or
more case or default labels.
• The switch statement evaluates its expression, then
executes all statements that follow the matching case label.
• Each break statement terminates the enclosing switch
statement.

• The break statements are necessary because without them,


statements in switch blocks fall through:
• All statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case
labels, until a break statement is encountered.
18
Switch Statement
• The switch statement can have a number of possible
execution paths.

switch(expression){
case value : //Statements
break; //optional
case value : //Statements
break; //optional //You can have any number of case
statements.
default : //Optional //Statements
}
• A switch works with the byte, short, char,
and int primitive data types.
19
Switch Statement
switch(expression) {
case value :
// Statements

break; // optional
case value :

// Statements

break; // optional

// You can have any number of


case statements.

default : // Optional

// Statements
}

20
Switch Statement
int month = 2;

String monthString;

switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
default:
monthString = "Invalid month";
break;
}
System.out.println(monthString);

******************************
February
21
Switch Statement
public class Test {
public static void main(String args[])
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done"); break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}} 22
Looping Statements
A loop statement allows us to execute a statement or group of
statements multiple times and following is the general form
of a loop statement in most of the programming languages:

23
while Loop
A while loop statement in java programming language repeatedly
executes a target statement as long as a given condition is true.

The syntax of a while loop is:

while(Boolean_expression) {
//Statements
}

• if the boolean_expression result is true, then the actions inside the


loop will be executed and it will be continued until the condition
becomes false.
• Key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false.

24
while Loop
class Testwhile {
public static void main(String args[]) {
int x = 10;
while( x < 13 ) {
System.out.print("value of x : " + x );
x++;
}
}}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12

25
while Loop
How to draw a flowchart to find the Fibonacci series till term≤1000 then
convert the flow cart to java code?
The Rule is xn = xn-1 + xn-2
Answer:
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

xn is term number "n"


xn-1 is the previous term (n-1)
xn-2 is the term before that (n-2)

Example: term 9 is calculated like this:


X9 = x9-1 + x9-2
= x8 + x7
= 21 + 13
= 34 26
while Loop
class fib{
public static void main(String[] args){
int fterm=0;
int sterm=1;
int temp=0;
while(fterm<=1000){
System.out.println(“Result = "+sterm);
temp=sterm;
sterm=sterm+fterm;
fterm=temp;

}
System.out.println("The number is
out of range!");
}}
27
do-while Statements
A do...while loop is similar to a while loop, except that a
do...while loop is guaranteed to execute at least one time.

do {
//Statements
}while(Boolean_expression);

• Notice that the Boolean expression appears at the end of the


loop, so the statements in the loop execute once before the
Boolean is tested.
• If the Boolean expression is true, the control jumps back up
to do statement, and the statements in the loop execute
again. This process repeats until the Boolean expression is
false.
28
do-while Statements
int i = 0;  
do{
System.out.println("i is : " + i +"\n");
i++;
}while(i < = 4);
}
}

Output would be:

i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
29
for Loop
For loop executes group of Java statements as long as the
boolean condition evaluates to true.
The syntax of a for loop is:

for(initialization; Boolean_expression; update) {


//Statements
}

• The initialization step is executed first, and only once. 


• Next, the Boolean expression is evaluated. If it is true, the
body of the loop is executed. If it is false, the body of the loop
will not be executed.
• Update statement is perfectly acceptable for this expression
to increment or decrement a value.
30
for Loop
class Testfor {
public static void main(String args[]) {
for(int x = 10; x < 15; x++) {
System.out.println("value of x : " + x );
}
}}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

31
Nested Loop
A nested loop is a (inner) loop that appears in the loop body of
another (outer) loop. The inner or outer loop can be any
type: while, do while, or for. For example, the inner loop can be
a while loop while an outer loop can be a for loop. Of course,
they can be the same kind of loops too.

for (int i = 1; i <= 5; i++) {


for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

32
Branching Statements
Branching statements: are used to transfer control to another
point in the code.
The Java programming language supports three branching
statements:
• The break statement.
• The continue statement.
• The return statement.

The break and continue statements have two forms:


• unlabelled form.
• labelled form(A label is an identifier followed by a colon).
Tips: The return statement is used to explicitly return from a
method
33
unlabelled break Statement
It is used to exit out of a loop.
We have already seen the use of the break statement in the
switch structure.

for (int i = 1; i <= 7; i++) {
System.out.println(i);
if (i == 4) {
break;
}
}

The above code will print the numbers from 1 to 4, one each
one line.

34
unlabelled break Statement
When loops are nested, the use of break will causes control to
move out of the loop to which the break statement belongs.

for ( ..... ) {
    for ( ..... ) {
        for ( ..... ) {
        }
        if ( ..... ) {
            break;
        }
    }
    // control shifts here
}
The break statement is a part of the second for loop.
35
labeled break 
class Testunlabel {
public static void main(String args[]) {
int[][] arrayOfInts = { { 55, 91, 84, 23 },{ 34, 88, 12, 56 }, { 129, 22, 77, 57 } };
int searchfor = 77;
int i, j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}}}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}}}
Found 77 at 2, 2

36
unlabeled break 
String[] names = { "Kurdistan", "Hunar", "Binar", "Shamal", "Hardi","Diare" };
String searchfor = "Binar";
int i;
boolean foundIt = false;
for (i = 0; i < names.length; i++) {
if (names[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}

Terminates the for loop when that value is found. This program's output


is:
Found Binar at index 2

37
unlabelled continue Statement
The continue keyword can be used in any of the loop control
structures. It causes the loop to immediately jump to the next
iteration of the loop.
class continueStat{
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x=0;x<numbers.length;x++ ) {
if( numbers[x] == 30 ) {
continue;
}
System.out.println( numbers[x] );
}}
}
38
Unlabeled Continue Statement
continue is used to escape current execution and transfers
control back to start of the loop. 

for(int var1 =0; var1 < 5 ; var1++)


{
for(int var2=0 ; var2 < 5 ; var2++)
{
if(var2 == 2)
continue;
System.out.println("var1:" + var1 + ", var2:"+ var2);
}
}

In above example, when var2 becomes 2, the rest of the inner


for loop body will be skipped.

39
Labeled Continue Statement
A labeled continue statement skips the current iteration of an
outer loop marked with the given label.

int count=1;
OuterLoop: for (int i = 1; i <= 5; i++) {
count = 1;
for (int j = 2; j <= i; j++) {
if (i > 4 && i % 2 == 1) {
continue OuterLoop;
}
count += j;
}
System.out.print(count);
}
}
}
The output is 1, 3, 6, 10
40
Labeled Continue Statement
Labeled continue statement skips the current iteration of the loop
marked with the specified label. This form is used with nested
loops.
Outer:
for(int var1 =0; var1 < 5 ; var1++)
{
        for(int var2=0 ; var2 < 5 ; var2++)
 {
if(var2 == 2)
continue Outer;
System.out.println(“var1:” + var1 + “, var2:”+ var2);
}
}
In the above example, when var2 becomes 2, rest of the statements
in body of inner as well outer for loop will be skipped, and next
iteration of the Outer loop will be executed.
41
return Statement
The return statement is used in methods to optionally return a
value and transfer control back to the calling method.

The return statement has two forms:

• one that returns a value.


• one that doesn't.

To return a value, simply put the value (or an expression that


calculates the value) after the return keyword.
return ++count;

42
return Statement
The data type of the returned value must match the type of
the method's declared return value.

int computeSize(int height, int width) {


return height * width;
}

When a method is declared void, use the form of return that


doesn't return a value.
return;
void computeSize(int height, int width) {
height * width;
}
43
return Statement
When a method is declared void, use the form of return that
doesn't return a value.
return;

In a void method, an implicit return is always at the end of


the method. But we can specify a return statement (with no
argument) to have an early exit.

void displayPassword(int Y) {
if (Y >= 5)
return;
System.out.println("Y is smaller or not equal of 5");
}

44
Exercises 1
• Use a for, while and Do while loop to print out the odd
numbers from 1 to 10.

• Write a java program to show Seven days in a week:


If S is entered tell us “Today is Sunday”……and so on.

• Make Flowchart and Pseudocode for students grading


System as showed below then convert to a java program.
Grading System: (50-59% Satisfactory), (60-69% Fair), (70-
79% Good), (80-89% Very Good) and (90-100% Excellent).
Write Java program to allow the user to input his/her age.
Then the program will show if the person is eligible to vote.
A person who is eligible to vote must be older than or equal
to 18 years old..
45
Exercises 2
Write a Java program by using three for loops to print the
following pattern:
1******

12*****

123****

1234***

12345**

123456*

46
Exercises 3
Write a java program to create Pyramid as showed below:
1
12
123
1234
12345

Write a java program to create Pyramid as showed below:


#####
####
###
##
#
47
References
Java in a Nutshell, 6th Edition, By David Flanagan,2015

Introduction to programing with java, John S.Dean,2008

http://java.sun.com/docs/books/tutorial

http://www.vogella.com

http://journals.ecs.soton.ac.uk/java/tutorial

48

You might also like