This document provides information about a course on fundamentals of Java programming taught by Khirulnizam Abd Rahman. It includes details about the instructor's background and programming experience, course synopsis and objectives, assessment methods, required textbooks, and an outline of topics to be covered such as control structures, methods, arrays, classes, and file I/O. The topic outline lists lessons on selection structures including if-else statements and switch cases, as well as repetition structures and nested control flows.
The document discusses different types of selection statements in C programming including if statements, else if statements, nested if statements, switch statements, and nested switch statements. It provides the syntax and examples of how to use each type of statement to control program flow based on logical expressions that evaluate to true or false. The if statement and switch statement allow executing different blocks of code conditionally based on the result of logical expressions or comparisons.
This document discusses different types of conditional statements in C programming including if, if-else, nested if-else, and else-if ladder statements. It provides examples of each type of conditional statement and explains their general forms and usage. The document also covers the switch statement in C, explaining its structure and providing an example.
This document discusses different types of flow control in Python programs. It explains that a program's control flow defines the order of execution and can be altered using control flow statements. There are three main types of control flow: sequential, conditional/selection, and iterative/looping.
Sequential flow executes code lines in order. Conditional/selection statements like if/else allow decisions based on conditions. Iterative/looping statements like for and while loops repeat code for a set number of iterations or as long as a condition is true. Specific conditional statements, loops, and examples are described in more detail.
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming languages:
The document discusses different types of loops in Java including while, do-while, and for loops. It explains the syntax and flow of each loop type and provides examples of how and when to use each loop. The document also covers break and continue statements that can be used inside loops to control flow, as well as increment and decrement operators.
Based on chapter 2 of the textbook "Building Java Programs", 3rd edition. Covers primitive data types, variables, operators, ASCII values for chars, operator precedence, String concatenation, casting, for loops, nested for loops, and class constants.
See a video presentation of this slideshow on my YouTube channel JavaGoddess, at https://www.youtube.com/watch?v=N7SBkMY65gc&t=4s
High School level (years 9-10 in Australia, ages 14-16) introduction to programming course, based on the language Processing, includes class material, exercises, examples, and tests. Course ran for 2 terms in 2014. Feel free to use as is, borrow ideas, etc. 3rd class.
Control statements allow different sets of instructions to be executed depending on logical conditions through branching and looping. Common control structures include if/else for conditional branching and while, do-while, for loops for repetition. These structures use relational, logical, and arithmetic operators to evaluate conditions that determine the flow of program execution.
The document provides examples of using MATLAB to perform calculations and functions. It demonstrates operations like matrix multiplication, taking the inverse of a matrix, reshaping arrays, and using functions like sort, sin, and cos. It also shows accessing elements of matrices and arrays, defining vectors and matrices, and returning errors when inputs are invalid.
The document provides information about Python programming language:
- Python was created in the late 1980s and became widely popular in the early 2000s.
- It is a high-level, general-purpose, interpreted programming language that can be used for web, desktop, game development, data science, and more.
- Some key features of Python include dynamic typing, automatic memory management, and being multi-paradigm supporting object-oriented, imperative, functional programming styles.
This document provides an overview of control structures in the C programming language. It discusses selection statements like if, if-else and switch statements that allow conditional execution of code. It also covers iteration statements like for, while and do-while loops that allow repetitive execution. Additionally, it explains jump statements like break, continue, goto and return that change the flow of control.
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
Exam Objective 4.2 Given an algorithm as pseudo-code, determine the correct scope for a variable used in the algorithm and develop code to declare variables in any of the following scopes: instance variable, method parameter, and local variable.
The document discusses different types of decision making and looping statements in C programming. It describes simple if, if-else, nested if-else, and else-if ladder statements for decision making. It also covers while, do-while, and for loops for iterative execution. Examples are provided for each statement type to illustrate their syntax and usage.
The code attempts to implement an interface method with a more restrictive access modifier, which causes a compilation error. The interface method is implicitly public, but the implementation tries to make it void instead of public. This violates the interface and results in compilation failure.
This document discusses control flow statements in C programming language. It describes if, switch, while, do-while, for statements that allow conditional execution and looping. Specific examples are provided to illustrate if/else, while, for loops. Additional features of for loops like initializing multiple variables, omitting sections, and nesting loops are covered. The break and continue statements are also explained for jumping out or skipping parts of a loop.
The document discusses various control structures in the C language including conditional statements like if, if-else-if and switch statements, as well as loops and the goto statement. It provides examples of using if statements to check for even or odd numbers, if-else-if to check positive, negative and zero numbers, and switch statements to check the modulus of a number. The break and goto statements are also explained briefly.
This document discusses various control structures in C programming language including if, if-else, nested if-else, switch, break, continue and ternary operators. It provides syntax and examples for each control structure. The if statement is used for simple decisions while if-else is used for two-way decisions. Nested if-else allows for multiple conditions to be checked. Switch statement compares a value to multiple cases. Break and continue statements are used to control loops. The ternary operator provides a short-hand for if-else statements. In the end, contact details are provided to learn more about programming courses.
Operators and expressions in c languagetanmaymodi4
what is operator in c language
uses of operator in c language
syatax of operator in c language
program of operator in c language
what is expressions in c language
use of expressions in c language
syantax of expressions in c language
The document discusses different types of control structures in Java, including sequential, selection, and repetition structures. It focuses on selection structures such as if, if-else, and switch statements. The if statement and if-else statement are explained with examples, including using logical operators and block statements. The switch statement is also covered, highlighting the use of break statements. Multiple selection structures like nested if statements are demonstrated.
The document discusses assignment operators and control structures in C#. It defines various assignment operators like +=, -=, etc. and explains their precedence and associativity. It then discusses sequential programming and introduces selection and repetition control structures like if, if/else, switch statements for selection and while, do/while, for statements for repetition. It provides examples of if, if/else and nested if/else statements. It also discusses logical operators, conditional operators and switch statements.
This document provides instructions on installing Python 3 on Ubuntu and Windows operating systems. It discusses installing Python 3.8 on Ubuntu using the apt install command and verifying the installation with the python --version command. It also outlines downloading the Python installer, running the executable, adding Python to environment variables, and verifying the installation on Windows. The document further explains installing iPython using pip and provides examples of using boolean values, conditionals, loops, functions, and strings in Python programs.
This document provides an overview of a 5-day Java programming workshop covering operators and conditionals. It discusses arithmetic, assignment, relational and logical operators as well as operator precedence. It also covers conditional statements using if/else and switch/case and provides examples of evaluating grades based on percentages. Additional learning resources on Java programming concepts and documentation are recommended.
The document discusses various Java control structures including boolean variables, if and if-else statements, and switch statements. It explains:
- Boolean variables store true/false values and are used to make conditional decisions in control structures.
- If statements allow executing code conditionally based on boolean expressions. If-else statements choose between two code blocks.
- Switch statements select code blocks based on an integer or character value using case labels.
- Nesting, boolean operators, and precedence rules allow complex conditional logic.
This document discusses selection structures like if and switch statements in C++. It provides syntax and examples of using if statements with single and multiple statements, one-way and two-way if statements, nested if statements, else-if construction, and the ternary operator. It also covers the syntax and use of switch statements, including using break, examples calculating grades and days of the week, and exercises calculating BMI and converting seconds to days/hours/minutes/seconds.
The document discusses decision control instructions in C programming using if, if-else and conditional operators. It explains the syntax and usage of if, if-else-else statements with examples. Logical operators like &&, || and ! are described along with their usage in combining conditions. The conditional operator ?: is introduced with examples. Different methods to solve problems using decision control structures like nested if-else, logical operators and else-if are presented with examples.
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
This document discusses multiple selection (nested if-else statements) and switch statements in Java. It provides the syntax for multiple selection, an example of using nested if-else statements to check if a number is positive, negative, or zero, and an example grading scheme that uses multiple selection. Switch statements are also covered, including that break statements are typically used to transfer control out of each case and that missing break statements can cause control to fall through to subsequent cases.
This document discusses control statements in C# programming. It covers algorithms, pseudocode, and the main control structures: sequence, selection (if/else statements), and repetition (loops). Specific topics covered include if and if/else statements, the switch statement, nested conditional logic, common errors, and a list of C# keywords. Pseudocode is presented as a way to plan programs before coding. Examples are provided to illustrate each control structure.
This document discusses various control statements in C programming language. It explains decision making statements like if, if-else and nested if-else statements which allow a program to make decisions based on certain conditions. It also covers selection statements like switch case and iteration statements like for, while and do-while loops that allow repetitive execution of code. Finally, it describes jump statements like break, continue and goto that change the normal sequential flow of program execution. Examples are provided for each statement to illustrate their usage.
This document outlines the key control structures in programming, including sequence, selection (if/else), and repetition (while, for). It provides examples of algorithms and pseudocode for calculating a class average using counter-controlled and sentinel-controlled repetition. The document also includes the C++ code for a program that calculates the class average based on grades entered by the user, with the option to terminate input by entering a sentinel value.
This document outlines an introductory chapter on control structures in programming. It discusses various programming concepts like algorithms, pseudocode, control structures including sequence, selection, and repetition structures. Specific control structures covered include if, if/else, while, for, switch, do/while, break and continue. Logical operators and the difference between equality and assignment operators are also mentioned. The chapter provides examples and case studies to explain counter-controlled and sentinel-controlled repetition with while loops. It introduces various C++ keywords and shows how pseudocode can be translated to C++ code. Flowcharts are used to visualize program flow and control structures.
This document outlines control structures in programming, including selection structures like if/else and repetition structures like while and for loops. It provides examples of algorithms using pseudocode and C++ code that employ counter-controlled and sentinel-controlled repetition. Key concepts covered include flowcharts, logical operators, and avoiding logic errors. Nested control structures and the switch statement are also discussed.
The document provides information about various C++ operators and control flow statements:
- It explains assignment operators like +=, -=, *=, /=, %= and the increment/decrement operators ++ and --.
- Conditional statements like if-else are discussed along with logical operators like &&, || and !. Nested if/else, else-if ladder and dangling else issues are covered.
- Flow charts are introduced as a way to visualize algorithms and conditional logic.
- The switch statement provides an alternative way to write multiple conditional checks compared to nested if/else.
- Examples are provided to illustrate concepts like precedence of logical operators, relational operators, and handling division by zero.
This document provides an introduction to Java programming concepts including what Java is, how to set up a Java development environment, basic Java code structure, variables, data types, arithmetic operations, conditional statements, loops, and getting user input. It covers elementary Java topics through examples and explanations. Key points include how to write, compile and run a simple Java program that prints "Hello World", how to declare and use variables of different data types, the different conditional statements (if, if-else, if-else-if-else), looping constructs (while, do-while, for), and taking user input using the Scanner class.
The document discusses various control flow statements in C programming language. It describes selection statements like if-else which allow a program to make decisions on the logical condition evaluated. It also covers iteration statements like while, do-while and for loops that allow repetitive execution of code. The switch statement provides an alternative to chained if-else conditions. Control flow statements allow writing powerful programs by selecting or repeating important sections of code conditionally.
This document provides an overview of algorithms and data structures in Java. It begins with an example of a basic Java program structure and comments. It then covers key concepts like variables, data types, control structures like if/else statements and loops (while, do-while, for). The document also discusses functions - how they are defined and used to organize code. Functions allow breaking programs into smaller, reusable parts. In summary, the document serves as an introduction to fundamental programming concepts in Java like program structure, variables, control flow, and functions.
This document provides an overview of control statements and loops in Java programming. It discusses different types of control statements like if, if-else, if-else-if, switch statements and jump statements like break, continue, return. It also covers different types of loops in Java - for, while, do-while loops along with examples. Key topics include the syntax and usage of different control structures, nested loops and labeled loops in Java.
Similar to Chapter 1 Nested Control Structures (20)
http://KOKUIS.my/html5
HTML5 – refers to the modern day of HTML which promotes native handling of video & audio & animation without having to install additional plugins to browser.
.
Bootstrap – A HTML framework supports responsive web design to provide one time webpage development for smartphone, tablet and desktop.
.
Mobirise – a free web design studio that support HTML5 & Bootstrap’s famous ‘block’ design.
This document discusses developing mobile web apps using HTML5, jQuery, and PhoneGap/Apache Cordova. It covers the hybrid approach of using HTML/CSS/JavaScript for the front-end and PhoneGap to package it as a native mobile app. Tools mentioned include Apache Cordova, Node.js, Eclipse, and Xcode. It provides an overview of key topics to be covered in subsequent days, such as the mobile web page structure using jQuery Mobile, connecting to online databases using PHP and MySQL, and building apps with PhoneGap Build.
The document discusses reading and writing text files in Java. It shows how to use the PrintWriter class to write data like names and scores to a text file. It then demonstrates using the Scanner class to read the data back from the file by parsing the strings and integers. The example writes two names and scores to a file, and then reads and prints out the same data.
The document discusses the File class in Java, which represents files and directories on disk without providing file processing capabilities. It describes the File class constructors and common methods like exists(), isFile(), isDirectory(), getPath(), and list(). Examples are provided to demonstrate analyzing a file or directory path specified by the user, including checking if it exists, retrieving information about it, and listing the contents if it is a directory. The document also notes some common errors like using \ instead of \\ in file paths in string literals.
1. Classes allow the creation of user-defined data types through the grouping of related data members and member functions.
2. Class members can be declared as private, public or protected and determine accessibility outside the class.
3. Methods are defined similarly to regular functions but can access any member of the class without passing them as parameters.
This document provides an overview and introduction to developing Android apps using a hybrid approach with HTML5, jQuery, Apache Cordova and the Android SDK. It begins with background information about the author and their experience developing Android apps. It then outlines an agenda for two days of training on this topic. The rest of the document addresses frequently asked questions about Android and the hybrid app development process through short explanations and diagrams. Key topics covered include what Android is, its architecture, tools used for hybrid app development like Cordova and Eclipse, and how to structure an Android project.
The document discusses arrays and motivates their use. It explains that arrays allow storing a large number of values in a program and accessing them through indices. Arrays solve the problem of having to declare many individual variables to store multiple values. The document then introduces the concept of arrays, how to declare and initialize array variables, and how to access elements within an array using indices. It provides examples of declaring, initializing, and accessing one-dimensional and two-dimensional arrays.
The document discusses defining and using methods in Java. It defines what a method is and its key components like the method signature, return type, parameters, and body. It then demonstrates a sample max method to return the maximum of two numbers and traces the steps of invoking the method from the main method, including passing arguments, executing the method body, and returning the result. The document aims to explain the basics of methods in Java, including how to define reusable methods and invoke them to perform certain tasks.
The document discusses defining and using methods in Java. It defines what a method is and its key components like the method signature, return type, parameters, and body. It then demonstrates a sample max method to return the maximum of two numbers and traces the steps of invoking the method from the main method, including passing arguments, executing the method body, and returning the result. The document aims to explain the basics of methods in Java, including how to define reusable methods and invoke them to perform certain tasks.
Dokumen tersebut membahas sejarah perkembangan ilmu pengetahuan dan masyarakat, termasuk definisi ilmu pengetahuan, pengaruh ilmu pengetahuan dalam peradaban dunia, era digital dan perbedaan antara masyarakat bermaklumat dengan masyarakat berpengetahuan.
This document discusses Islam in the era of information and communication technology (ICT). It states that Islam's core belief is that Allah is the creator of all things, and that the purpose of creation is for humans to worship Allah and act as stewards of the earth. While ICT provides benefits, it also poses challenges like the spread of false information and exposure of youth to inappropriate content without oversight. The document argues that Islamic principles of maintaining balance, protecting faith, life, intellect and society, and eliminating harm can help address issues in the ICT era.
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Khirulnizam Abd Rahman
Application of Ontology in Semantic Information Retrieval
by Prof Shahrul Azman from FSTM, UKM
Presentation for MyREN Seminar 2014
Berjaya Hotel, Kuala Lumpur
27 November 2014
This course is the continuation of the previous course (Algorithm and Problem Solving). It introduces complex flow control, method, array, class design, file and file I/O.
Kursus ini membincangkan adab pengendalian maklumat, isu-isu yang berkaitan dengan teknologi komputer dan teknologi maklumat. Penggunaan komputer peribadi dengan memberi pendedahan kepada perkakasan dan perisian komputer. Membincangkan mengenai internet, telekomunikasi serta pencarian maklumat melalui web. Membentuk pelajar yang beradab dalam pengendalian dan pengurusan maklumat.
This document provides guidance on writing a review paper in 3 sentences or less. It outlines the simple skeleton of a review paper including the title, affiliation, abstract, introduction, previous works, and conclusion sections. The document recommends reading sample papers and provides page by page guidance for completing each section of the paper within the 5 page limit. It emphasizes gaining experience by writing and encourages participants to draft their paper.
(T.L.E.) Agriculture: Essentials of GardeningMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏.𝟎)-𝐅𝐢𝐧𝐚𝐥𝐬
Lesson Outcome:
-Students will understand the basics of gardening, including the importance of soil, water, and sunlight for plant growth. They will learn to identify and use essential gardening tools, plant seeds, and seedlings properly, and manage common garden pests using eco-friendly methods.
Views in Odoo - Advanced Views - Pivot View in Odoo 17Celine George
In Odoo, the pivot view is a graphical representation of data that allows users to analyze and summarize large datasets quickly. It's a powerful tool for generating insights from your business data.
The pivot view in Odoo is a valuable tool for analyzing and summarizing large datasets, helping you gain insights into your business operations.
Integrated Marketing Communications (IMC)- Concept, Features, Elements, Role of advertising in IMC
Advertising: Concept, Features, Evolution of Advertising, Active Participants, Benefits of advertising to Business firms and consumers.
Classification of advertising: Geographic, Media, Target audience and Functions.
Front Desk Management in the Odoo 17 ERPCeline George
Front desk officers are responsible for taking care of guests and customers. Their work mainly involves interacting with customers and business partners, either in person or through phone calls.
How to Create Sequence Numbers in Odoo 17Celine George
Sequence numbers are mainly used to identify or differentiate each record in a module. Sequences are customizable and can be configured in a specific pattern such as suffix, prefix or a particular numbering scheme. This slide will show how to create sequence numbers in odoo 17.
No, it's not a robot: prompt writing for investigative journalismPaul Bradshaw
How to use generative AI tools like ChatGPT and Gemini to generate story ideas for investigations, identify potential sources, and help with coding and writing.
A talk from the Centre for Investigative Journalism Summer School, July 2024
How to Handle the Separate Discount Account on Invoice in Odoo 17Celine George
In Odoo, separate discount account can be set up to accurately track and manage discounts applied on various transaction and ensure precise financial reporting and analysis
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894PECB
As artificial intelligence continues to evolve, understanding the complexities and regulations regarding AI risk management is more crucial than ever.
Amongst others, the webinar covers:
• ISO/IEC 42001 standard, which provides guidelines for establishing, implementing, maintaining, and continually improving AI management systems within organizations
• insights into the European Union's landmark legislative proposal aimed at regulating AI
• framework and methodologies prescribed by ISO/IEC 23894 for identifying, assessing, and mitigating risks associated with AI systems
Presenters:
Miriama Podskubova - Attorney at Law
Miriama is a seasoned lawyer with over a decade of experience. She specializes in commercial law, focusing on transactions, venture capital investments, IT, digital law, and cybersecurity, areas she was drawn to through her legal practice. Alongside preparing contract and project documentation, she ensures the correct interpretation and application of European legal regulations in these fields. Beyond client projects, she frequently speaks at conferences on cybersecurity, online privacy protection, and the increasingly pertinent topic of AI regulation. As a registered advocate of Slovak bar, certified data privacy professional in the European Union (CIPP/e) and a member of the international association ELA, she helps both tech-focused startups and entrepreneurs, as well as international chains, to properly set up their business operations.
Callum Wright - Founder and Lead Consultant Founder and Lead Consultant
Callum Wright is a seasoned cybersecurity, privacy and AI governance expert. With over a decade of experience, he has dedicated his career to protecting digital assets, ensuring data privacy, and establishing ethical AI governance frameworks. His diverse background includes significant roles in security architecture, AI governance, risk consulting, and privacy management across various industries, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: June 26, 2024
Tags: ISO/IEC 42001, Artificial Intelligence, EU AI Act, ISO/IEC 23894
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
How to Add Colour Kanban Records in Odoo 17 NotebookCeline George
In Odoo 17, you can enhance the visual appearance of your Kanban view by adding color-coded records using the Notebook feature. This allows you to categorize and distinguish between different types of records based on specific criteria. By adding colors, you can quickly identify and prioritize tasks or items, improving organization and efficiency within your workflow.
Webinar Innovative assessments for SOcial Emotional SkillsEduSkills OECD
Presentations by Adriano Linzarini and Daniel Catarino da Silva of the OECD Rethinking Assessment of Social and Emotional Skills project from the OECD webinar "Innovations in measuring social and emotional skills and what AI will bring next" on 5 July 2024
Join educators from the US and worldwide at this year’s conference, themed “Strategies for Proficiency & Acquisition,” to learn from top experts in world language teaching.
Configuring Single Sign-On (SSO) via Identity Management | MuleSoft Mysore Me...
Chapter 1 Nested Control Structures
1. Fundamentals of (Java) Programming
Khirulnizam Abd Rahman
0129034614 (WhatsApp/SMS)
Khirulnizam@gmail.com
KERUL.net
2. About Khirulnizam
Lecturer of Computer Science, Faculty of Information Science and
Technology, Selangor International Islamic University College
(KUIS) – since 2000.
Codes in blog.kerul.net
Programming background: C, Java, PHP.
Apps in Google Play
M-Mathurat – 200K ( bit.ly/m-mathurat )
Peribahasa Dictionary – 20K ( bit.ly/pbahasa)
mDictionary – open-sourced ( bit.ly/m-dictionary )
Hijrah Rasul – bit.ly/hijrah-rasul
SmartSolat – bit.ly/smartsolat
Apps in Windows Store
Hijrah Rasul – bit.ly/hijrah-en
Peribahasa Dictionary
2 http://blog.kerul.net 11/28/14
3. Course Synopsis
This course is the continuation of the previous course (Algorithm
and Problem Solving). It introduces complex flow control,
method, array, class design, file and file I/O.
Objectives: At the end of this course, students should be able
to;
write and apply complex control structure.
create and invoke methods in programs.
declare, create and apply arrays and classes.
retrieve from and write data into another file.
Java Programming: From Problem Analysis to
3 Program Design, 3e
5. Main Text
Liang Y. Daniel. Introduction to Java Programming, Eight
Edition, 2011, Pearson
F. Joyce. Java Programming, 6th Edition, 2011, Course
Technology
Tool: JDK & Eclipse Java IDE
Java Programming: From Problem Analysis to
5 Program Design, 3e
7. Control Structures
A computer can process a program in three(3) ways :
Sequence (line by line)
Selection or choice (branch)
Repetition
8. Sequence Structure
Start at the beginning and follows the statement in order.
start
statement1
statement2
…
Statement-n
End
9. Selection Structure
Statement executions is depending on one or more condition
start
statement1
statement3 Fcondition T
statement2
Statement-n
End
10. Repetition Structure
Same statement is repeated in a number of times depending
on one or more condition.
start
statement1
statement2
condition
Statement-n
End
T
F
11. Conditional Expression Consider the following statement
If (score is greater than or equal to 90)
grade is A
If (temperature is greater than 50)
display “Its Hot”
Conditional
expression
Grade is A only if score
>=90
Display Its Hot only if the
temperature > 50
12. Logical Expression
Write the logical expression for the following
1. yourAge is greater than 50.
2. The value of myAge is not 0.
3. y is between 20 and 100
4. height is between 1.5 and 2.0.
13. Logical Expression
Use Logical & comparison operator to construct the
logical expression
1. yourAge > 50
2. myAge != 0
3. y > 20 && y <100
4. height > 1.5 && height < 2.0.
14. Logical Expression
Evaluate the following expression. Given x is 5 and y is
200.
1. x != 12
2. y < 100
3. x == 5
4. y == x*40
5. x >=5 && x <=5
6. y == 200 || y ==100
7. x == 10 || x != 5
15. Logical Expression
Evaluate the following expression. Given x is 5 and y is 200.
1. x != 12
2. y < 100
3. x == 5
4. y == x*40
5. x >=5 && x <=5
6. y == 200 || y ==100
7. x == 10 || x != 5
17. Selection Structure – If Statement
There are 3 types of if statement
One-way selection : if
Two-way selection : if - else
Multiple-way selection : if – else if - else
18. If Statement : One-Way IF
The Syntax
If (condition)
statement;
if (condition)
{
statement1;
statement2;
}
Only one
statement
More than one
statement
19. If Statement : One-Way If
If (condition)
statement1;
statement2;
T F
If (mark > 50)
F
System.out.println(“GOOD!!”);
System.out.println(“THANK YOU”);
Output :
THANK YOU
Mark = 34
20. If Statement : One-Way If
If (condition)
statement1;
statement2;
T F
If (mark > 50)
Mark = 60
T
System.out.println(“GOOD!!”);
System.out.println(“THANK YOU”);
Output :
GOOD!!
THANK YOU
21. If Statement : One-Way If
If (mark > 50){
Mark = 45
F
System.out.println(“GOOD!!”);
System.out.println(“GRAGE = A!!”);
}
System.out.println(“THANK YOU”);
Output :
THANK YOU
22. If Statement : One-Way If
If (mark > 50){
Mark = 60
T
System.out.println(“GOOD!!”);
System.out.println(“GRAGE = A!!”);
}
System.out.println(“THANK YOU”);
Output :
GOOD!!
GRADE = A
THANK YOU
23. If Statement : Two-Way IF
The Syntax
if (condition)
statement1;
else
statement2;
statement3;
Only one statement
for each
24. If Statement : Two-Way IF
The Syntax
if (score > 50)
F Mark = 34
System.out.println(“GOOD!!”);
else
System.out.println(“BAD!!”);
System.out.println(“THANK YOU”);
Output :
BAD!!
THANK YOU
25. If Statement : Two-Way IF
The Syntax
if (score > 50)
T Mark = 60
System.out.println(“GOOD!!”);
else
System.out.println(“BAD!!”);
System.out.println(“THANK YOU”);
Output :
GOOD!!
THANK YOU
26. If Statement : Two-Way IF
The Syntax
if (condition)
{
statement1;
statement2;
}
else
{
Statement3;
Statement4;
}
Statement5;
More than one
statement
27. If Statement : Two-Way IF
The Syntax
if (score > 50){
T Mark = 60
System.out.println(“GOOD!!”);
System.out.println(“GRADE = A!!”);}
else
System.out.println(“BAD!!”);
System.out.println(“THANK YOU”);
Output :
GOOD!!
GRADE = A
THANK YOU
28. If Statement : Two-Way IF
The Syntax
if (score > 50){
F Mark = 40
System.out.println(“GOOD!!”);
System.out.println(“GRADE = A!!”);}
else
System.out.println(“BAD!!”);
System.out.println(“THANK YOU”);
Output :
BAD!!
THANK YOU
29. If Statement : Multiple-Way IF
The Syntax
if (condition)
statement1;
else if (condition){
statement2;
statement3;}
else if (condition)
statement4;
else if (condition)
statement5;
else {
statement6;
statement7;}
Use braces if there
are more than one
statement in a group
30. If Statement : Multiple-Way IF
The Syntax
if (mark > 70)
grade = “A”;
else if (mark > 60 && mark <= 70){
grade = “B”;
mark = mark + 3;}
else if (mark > 50 && mark <=60)
grade = “C”;
else if (mark > 35 && mark <=50)
grade = “D”;
else {
grade = “F”
message = “FAIL!!!”}
Don’t use
60 < mark <=70 x
31. Output :
Grade = F
If Statement : Multiple-Way IF
if (mark > 70)
grade = “A”;
F Mark = 34?
F
else if (mark > 60 && mark <= 70){
grade = “B”;
mark = mark + 3;}
F
else if (mark > 50 && mark <=60)
grade = “C”;
else if (mark > 35 && mark <=50)
grade = “D”;
else {
grade = “F”
message = “FAIL!!!”}
T
System.out.println(“Grade = “ + grade);
32. If Statement : Multiple-Way IF
if (mark > 70)
grade = “A”;
F Mark = 65?
T
else if (mark > 60 && mark <= 70){
grade = “B”;
mark = mark + 3;}
else if (mark > 50 && mark <=60)
grade = “C”;
else if (mark > 35 && mark <=50)
grade = “D”;
else {
grade = “F”
message = “FAIL!!!”}
Output :
Grade = B
System.out.println(“Grade = “ + grade);
33. Selection Structure : Switch
switch(expression) { //start switch
case value1:
statement1;
break;
case value2:
statement2;
statement3;
break;
case value3:
statement4;
break;
…
default:
statement-n;
} // end switch
use colon
not semicolon
34. Selection Structure : Switch
switch(month) { //start switch
case 1:
Name = “January”;
break;
case 2:
name = “February”;
break;
case 3:
name = “March”;
break;
…
default:
name = “ Not available”;
} // end switch
System,out.println(“Month = “ + name);
Month = 2
F
T
35. C1 - COMPLEX FLOW CONTROL
FUNDAMENTALS OF PROGRAMMING
DTCP 2023
36. NESTED IF STATEMENT
SYNTAX
if (Boolean_Expression_1)
if (Boolean_Expression_2)
Statement_1)
else
Statement_2
37. Nested Statements
Subtly different forms
First Form
if (a > b)
{
if (c > d)
e = f
}
else
g = h;
Second Form
if (a > b)
if (c > d)
e = f
else
g = h;
// oops
38. What is the output? Any difference???
if ( x < y)
if (x < z)
System.out.println("Hello");
else
System.out.println("Good bye");
if ( x < y){
if (x < z)
System.out.println("Hello");
}else
Good bye
System.out.println("Good bye");
Nested if statement
No output given
39. The Nested-if Statement
The then and else block of an if statement can contain any valid
statements, including other if statements. An if statement
containing another if statement is called a nested-if statement.
39
if (testScore >= 70) {
if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >=
70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
40. Control Flow of Nested-if Statement
false inner if
messageBox.show
("You did not
pass");
40
messageBox.show
("You did not
pass");
false
testScore >= 70
?
testScore >= 70
?
messageBox.show
("You did pass");
messageBox.show
("You did pass");
true
studentAge < 10
?
studentAge < 10
?
true
messageBox.show
("You did a great
job");
messageBox.show
("You did a great
job");
41. Nested if-else Statements
An if-else statement can contain any sort of statement
within it.
In particular, it can contain another if-else statement.
An if-else may be nested within the "if" part.
An if-else may be nested within the "else" part.
An if-else may be nested within both parts.
42. Nested Statements
Syntax
if (Boolean_Expression_1)
if (Boolean_Expression_2)
Statement_1)
else
Statement_2)
else
if (Boolean_Expression_3)
Statement_3)
else
Statement_4);
43. Nested Statements
Each else is paired with the nearest unmatched if.
If used properly, indentation communicates which if goes
with which else.
Braces can be used like parentheses to group statements.
44. TRACE THE OUTPUT
public class test{
public static void main(String[] args){
int a=4;
for (int i=1; i<a;i++ ){
for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
* **
***
45. EXERCISE
Construct a simple program that apply nested if else statement
follow the rules given.
Score Grade
90 <= score A
80 <= score < 90 B
70 <= score < 80 C
60 <= score < 70 D
Score < 60 F
Example:
If student score is 99 then display the grade which is A to student.
46. 46
Nested if Statements
The statement executed as a result of an if statement or
else clause could be another if statement
These are called nested if statements
See MinOfThree.java (page 227)
An else clause is matched to the last unmatched if (no
matter what the indentation implies)
Braces can be used to specify the if statement to which an
else clause belongs
48. Example 1
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
48
Output:
*
**
***
****
*****
49. Example 2
What will be the value of after each of the following nested
loops is executed?
for (int i = 1; i < 4; i++){
for (int j = 1; j < 4-i; j++){
System.out.print(" *");
} System.out.println();
}
49
Output:
**
*
50. Example 3
What will be the value of after each of the following nested
loops is executed?
int sum = 0;
for (int i = 0; i<=2; i++)
{ for (int j = 0; j<=2; j++)
{ sum = sum + i;
}
}System.out.println(sum);
50
Output:
9
51. Example 4
What does the following program segment print?
for (int f = 0; f < 3; ++f){
for (int g = 0; g < 2; ++g){
System.out.print(f);
System.out.print(g);
}
}
51
Output:
000110112021
52. Nested Loops
Suppose you wanted to print the following table:
for (int row = 1; row <= 4; row++) { // For each of 4 rows
for (int col = 1; col <= 9; col++) // For each of 9 columns
System.out.print(col * row + "t"); // Print 36 numbers
System.out.println(); // Start a new row
} // for row
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
• You could use a nested for loop. The outer loop
prints the four rows and in each row, the inner loop
prints the 9 columns.
53. Nested Loops (cont.)
The table shows the relationship between the row and
column variables needed to print the following triangular
pattern:
# # # # #
# # # #
# # #
# #
#
• You could use the following nested for loop.
for (int row = 1; row <= 5; row++) { // For each row
for (int col = 1; col <= 6 - row; col++) // Print the row
System.out.print('#');
System.out.println(); // And a new row
} // for row
Row Column Bound
(6 – Row)
Number of
Symbols
1 6-1 5
2 6-2 4
3 6-3 3
4 6-4 2
5 6-5 1
54. The Nested-for Statement Nesting a for statement inside another for statement is commonly
used technique in programming.
Let’s generate the following table using nested-for statement.
54
55. 55
Generating the Table
int price;
for (int width = 11; width <=20, width++){
for (int length = 5, length <=25, length+=5){
price = width * length * 19; //$19 per sq. ft.
System.out.print (“ “ + price);
}
//finished one row; move on to next row
System.out.println(“”);
RENNI
}
RETUO
Editor's Notes
It is possible to write if tests in different ways to achieve the same result. For example, the above code can also be expressed as
if (testScore &gt;= 70 && studentAge &lt; 10) {
messageBox.show(&quot;You did a great job&quot;);
} else {
//either testScore &lt; 70 OR studentAge &gt;= 10
if (testScore &gt;= 70) {
messageBox.show(&quot;You did pass&quot;);
} else {
messageBox.show(&quot;You did not pass&quot;);
}
}
This diagram shows the control flow of the example nested-if statement.
Just an if statement can be nested inside another if statement, we often nest for loops. For example, using a nest-for loop is the most appropriate way to generate a table such as the illustration.
Here&apos;s how the table can be produced by a nested-for loop.
For each value of width, length will range from 5 to 25 with an increment of 5. Here’s how the values for width and length change over the course of execution.
widthlength
11
5
10
15
20
25
12
5
10
15
20
25
13
5
10
and so on…