The document discusses different types of loops in Java including while loops, do-while loops, and indefinite loops using sentinels. It provides examples of using random numbers and boolean return values from methods to implement program logic within loops. Key concepts covered include fencepost problems, random number generation, and using boolean values to represent logical tests.
The document discusses various Java programming concepts including enumerated types, repetition statements like while, do-while and for loops, and arrays. It provides examples of using enumerated types to define variables of a custom type. It explains the logic and usage of while, do-while and for loops, including examples calculating averages and percentages. It also demonstrates how nested loops can be used to print patterns. Finally, it introduces arrays as ordered lists of values that can be accessed using an index.
The document discusses for loops in Java including their syntax, examples of using for loops to print numbers, infinite loops, breaking and continuing loops, and nested for loops. It provides examples of using for loops to generate Fibonacci sequences, factorials, prime numbers, and nested patterns.
Java Chapter 05 - Conditions & Loops: part 5DanWooster1
The document discusses loops in Java programming. It defines loops as repetition statements that allow a program to execute a statement multiple times. The while loop executes a statement repeatedly until a condition becomes false. Key aspects covered include the syntax of a while loop, the logic of evaluating the condition each repetition, using sentinel values to terminate loops, nested loops, and avoiding infinite loops.
This chapter discusses different types of repetition statements in Java including while, do-while, for, and nested loops. It covers implementing repetition using these statements, choosing the appropriate one for a given task, and avoiding common pitfalls like off-by-one errors and infinite loops. Examples are provided to demonstrate generating tables with nested for loops and formatting output using the Formatter class.
The document provides examples of using Java code to solve problems with algorithms involving loops, recursion, and other control structures. It includes examples calculating sums, factorials, products, powers, checking for primes, and printing patterns using nested loops. It discusses concepts like recursion, break and continue operators, and exercises for the reader to implement programs involving sequences, matrices, and factorials.
This document provides instructions for Lab 2 of an Introduction to Java Technologies course. It includes prelab exercises on control flow and arrays, an activity demonstrating the different meanings of the + operator in Java, an activity modifying a sales data program, and an activity analyzing and coding a program to calculate average ratings from user-item rating data. Students are asked to complete the programming activities, submit a zip file of their source code, and a lab report answering the prelab questions and providing a conclusion. The report must be in Word or PDF format and include a cover page with specified information.
This lecture discusses loops and looping constructs in Java programming. The instructor begins by clarifying the proper use of casts when converting between data types. They then discuss the "loop and a half" pattern, where code is executed at least once before entering the loop. They demonstrate using a while(true) loop with a break statement to avoid duplicating code. Finally, the instructor shows how to draw a checkerboard using nested for loops, constants for the board size, and graphics rectangles. The key topics covered are casts, indefinite loops, the loop and a half pattern, and applying loops to a graphics example.
more loops lecture by Professor Evan korth hammad ali
The document summarizes an upcoming lecture on loops. It provides the schedule, outlines topics to be covered including sentinels, sentinel-controlled loops, and nested control structures. Examples of using sentinels to end a loop based on user input and a case study on analyzing test results are discussed. Key terms like sentinel, initialization, processing, and termination are also introduced.
Q3 GIVEN THE TREND EQUATION NO OF STUDENTS-3000+200 YEAR BASE: 2003-0
1.INTERPRET EQUATION RESULTS 2.FORECAST FOR 2020 3.WHEN WILL THE NO OF
STUDENTS REACH 6000
Solution
x no of years from 2003 y no of students y = 3000+200x 1) The regression
equation has a positive slope of 200 y intercept is 3000 i.e. no of students in the year 2000
Thus for every year 200 students increase 2) For 2020, x = 17, y = 3000+200(17) = 6400
3) When y =6000, 6000 = 3000+200x or x = 15 Hence in year 2018 students reach 6000
B Regression C D. All the above.
This chapter discusses repetition and looping control structures in Java, including while, for, and do-while loops. It provides examples of using these loops, such as printing numbers in a range or calculating Fibonacci numbers recursively. The chapter also covers statements for early loop exit like break and continue, and nesting control structures for increased complexity.
The document discusses different types of loops in Java including while, do-while, for, nested, and loops using break and continue statements. It provides examples of a guessing game program using a do-while loop that repeatedly prompts the user for a guess and checks if it matches a random number. It also gives short code examples demonstrating the basic syntax of for, nested, and loops with break and continue.
This document provides an overview of loops in Java, including for, while, do-while loops as well as break and continue statements. It discusses using loops to iterate through arrays or to repeatedly execute blocks of code when the number of iterations is predictable or unpredictable. Examples are provided to calculate factorials using different loop types and to demonstrate the break and continue statements. Additional learning resources on Java programming concepts are also listed.
The document discusses various programming concepts in C# such as data types, control flow statements like if/else, switch, loops (for, while, do-while), methods for generating random numbers, and examples of programming problems involving calculations, patterns, and simulating dice rolls. Random numbers can be generated using the Random class, control structures conditionally execute blocks of code, and loops iterate code for a set number of repetitions.
This document discusses different types of loops in Java including while, do-while, and for loops. It explains the syntax and flow control of each loop type. Examples are provided to demonstrate how to use loops appropriately. Common mistakes like infinite loops and off-by-one errors are highlighted. The break and continue keywords are also explained. Finally, the document briefly introduces methods in Java.
The document discusses various programming concepts in C# such as random number generation, Boolean expressions, control statements like if/else, switch, for, while and do-while loops. It also covers nested loops, break and continue statements, and provides examples of problems that can be solved using these programming constructs like generating random numbers, printing patterns, and simulating dice rolls.
The document discusses different types of loops in Java including while, do-while, and for loops. It provides examples of using each loop type to repeatedly print a string, generate math quiz questions, and calculate a sum of user inputs. Key aspects covered include initializing and updating a loop counter, loop continuation conditions, and using loops with sentinel values to control the number of iterations.
The document discusses different types of repetition structures in Java programming such as while, for, and do-while loops. It provides examples of how to use each loop type and when each is best suited depending on whether the number of iterations is known. The document also covers break and continue statements that can be used to exit or skip iterations in loops.
The document discusses different types of repetition structures in Java programming such as while, for, and do-while loops. It covers how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled loops. Examples are provided to illustrate different types of loops and how to choose the appropriate one for a given programming problem.
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.
Which if statement below tests if letter holds R (letter is a char .pdfaniarihant
Which if statement below tests if letter holds R? (letter is a char variable)
if ( letter == \"R\")
if ( letter >= \'R\')
if ( letter == R)
if ( letter = \'R\')
if ( letter == \'R\')
What are if statements used for in programs?
Repeating commands
Storing data
Numeric calculations
Numeric casts
Making decisions
The following if statement tests the rainfall in New York’s Central Park during the months of
June, July and August.
if (low <= rain && rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
It could be replaced with:
I.
if (rain >= low)
{
if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
}
else
System.out.println(\"Rainfall amount is abnormal.\");
II.
if (rain >= low)
{
if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
}
else
System.out.println(\"Rainfall amount is abnormal.\");
III.
if (rain >= low)
System.out.println(\"Rainfall amount is normal.\");
else if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
I only
II only
III only
II or III
I, II or III
What is output by the following code?
int x = 36 % 8;
if (x >= 10)
System.out.println( 1);
else if (x >= 8)
System.out.println( 2);
else if (x >= 6)
System.out.println( 3);
else if ( x >= 4)
System.out.println( 4);
else
System.out.println( 5);
1
2
3
4
5
Consider the code:
if ( y == 0 || x * y > 10)
Which of the following is an example of short circuit evaluation?
if x * y > 10 is false it evaluates y ==0
if x * y > 10 is false it doesn\'t evaluate y ==0
if y == 0 is false it doesn\'t evaluate x * y > 10
if y == 0 is true it doesn\'t evaluate x * y > 10
if y == 0 is false it evaluates x * y > 10
The following truth table matches which boolean condition?
A && ( A || B)
A || ( !A && !B)
A && ( A && B)
!A && ( A || !B)
A || ( A || B)
Consider the code:
if (a < b && c != d)
Which of the following is an example of short circuit evaluation?
if a < b is true it doesn\'t evaluate c != d
if a < b is false it doesn\'t evaluate c != d
if c != d is false it evaluates a < b
if c != d is true it doesn\'t evaluate a < b
if a < b is true it evaluates c != d
! ( x < y && w == z) is the same as which boolean expression?
x <= y && w == z
x >= y || w != z
x <= y || w != z
x <= y && w != z
x < y && w != z
Assume that x and y are boolean variables and have been properly initialized.
!(x || y) || (x || y)
The result of evaluating the expression above is best described as:
always true
always false
true only when x is true and y is true
true only when x and y have the same value
true only when x and y have different values
What is output to the screen by the following code?
int c = 2;
while (c < 6)
{
System.out.print((int)Math.pow (-1, c)+\" \");
c++;
}
-1 1 -1 1 -1 1 -1
1 -1 1 -1
-1 1 -1 1 -1 1
1 1 1 1 1 1
-1 -1 -1 -1 -1 -1
How many times will the following loop repeat?.
The document discusses looping statements and examples of using while and for loops to repeatedly execute blocks of code. It provides examples of using loops to generate math quiz questions, guess random numbers, calculate sums, and find greatest common divisors. It also discusses using break and continue statements, nested loops, minimizing numerical errors, and Monte Carlo simulations.
This document contains code snippets and explanations related to Java programming concepts like classes, objects, methods, conditionals, loops, and arrays. It begins with simple examples of printing text and using methods. It then covers more complex topics like defining classes with fields and methods, if/else and switch conditional statements, for, while, and do-while loops, parsing user input, and creating and accessing objects. The document appears to be notes or exercises for learning Java programming fundamentals through worked examples and explanations.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This document appears to be an assignment submission for a post graduate diploma in information technology. It contains 10 questions related to Java programming and the answers/code snippets provided for each question. The questions cover topics like simple interest calculation, sum of digits, Fibonacci series, converting decimal to Roman numerals, prime numbers, nested for loops to print patterns, recursive factorial, defining custom exceptions and creating a simple welcome applet.
CMIS 102 Hands-On Lab
// Week 4
Overview:
This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, analysis, test plan, design (using both flow chart and pseudocode visualization), and implementation with C code. The example provided uses sequential, selection and repetition statements.
Program Description:
This program will calculate the sum of 10 integers. The program will ask the user to 10 integers. If the sum of the numbers is greater than 1000, a message is printed stating the sum is over 1000. The design step will include both pseudocode and flow chart visualization.
Analysis:
I will use sequential, selection and repetition programming statements.
I will define three integer numbers: count, value, sum. Count will store how many times values are entered to make sure we don’t exceed 10 values. Value will store the input integer and sum will store the running sum.
The sum will be calculated by this formula:
sum = sum + value
For example, if the first value entered was 4 and second was 10:
sum = sum + value = 0 + 4
sum = 4 + 10 = 14
Values and sum can be input and calculated within a repetition loop:
while count <10
Input value
sum = sum + value
End while
The additional selection statement will be of this form:
If sum > 1000 then
print "Sum is over 1000"
End If
Test Plan:
To verify this program is working properly the input values could be used for testing:
Test Case
Input
Expected Output
1
value=1
value=1
value=1
value=0
value=1
value=2
value=0
value=1
value=3
value=2
Sum = 12
2
value=100
value=100
value=100
value=100
value=100
value=200
value=200
value=200
value=200
value=200
Sum = 1200
Sum is over 1000.
3
value=-100
value=-100
value=-200
value=0
value=200
value=100
value=0
value=200
value=-300
value=-200
Sum = -400
Pseudocode:
// This program will calculate the sum of 10 integers.
// Declare variables
Declare count, value, sum as Integer
//Initialize Counter, Sum to 0
Set count=0
Set sum = 0
// Loop through 10 integers
While count < 10
Print “Enter an Integer”
Input value
sum = sum + value
count=count+1
End While
// Print results and messages
Print “Sum is “ + sum
If (sum > 1000)
Printf “Sum is over 1000”
End if
Flow Chart:
C Code
The following is the C Code that will compile in execute in the online compilers.
// C code
// This program will calculate the sum of 10 integers.
// Developer: Faculty CMIS102
// Date: Jan 31, 2014
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
/* Initialize count and sum */
count = 0;
sum = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter an Integer\n");
scanf("%d", &value);
sum = sum + value;
count = count + 1;
}
printf("Sum is %d\n " , sum );
if (sum >1000)
printf("Sum is over 1000\n");
return 0;
}
Setting up the code and the input parameters in ideone.com:
Note the input integer.
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
This document discusses file processing in Java. It covers topics like creating File objects, reading and writing files with Scanners and PrintWriters, handling exceptions when reading files, and processing file input line by line or token by token. Examples are provided to demonstrate reading numeric data from files and calculating values based on the data. The key aspects are using Scanners to read files, handling exceptions, and choosing between line-based and token-based processing depending on the file format.
More Related Content
Similar to ch05-program-logic-indefinite-loops.ppt (20)
This lecture discusses loops and looping constructs in Java programming. The instructor begins by clarifying the proper use of casts when converting between data types. They then discuss the "loop and a half" pattern, where code is executed at least once before entering the loop. They demonstrate using a while(true) loop with a break statement to avoid duplicating code. Finally, the instructor shows how to draw a checkerboard using nested for loops, constants for the board size, and graphics rectangles. The key topics covered are casts, indefinite loops, the loop and a half pattern, and applying loops to a graphics example.
more loops lecture by Professor Evan korth hammad ali
The document summarizes an upcoming lecture on loops. It provides the schedule, outlines topics to be covered including sentinels, sentinel-controlled loops, and nested control structures. Examples of using sentinels to end a loop based on user input and a case study on analyzing test results are discussed. Key terms like sentinel, initialization, processing, and termination are also introduced.
Q3 GIVEN THE TREND EQUATION NO OF STUDENTS-3000+200 YEAR BASE: 2003-0
1.INTERPRET EQUATION RESULTS 2.FORECAST FOR 2020 3.WHEN WILL THE NO OF
STUDENTS REACH 6000
Solution
x no of years from 2003 y no of students y = 3000+200x 1) The regression
equation has a positive slope of 200 y intercept is 3000 i.e. no of students in the year 2000
Thus for every year 200 students increase 2) For 2020, x = 17, y = 3000+200(17) = 6400
3) When y =6000, 6000 = 3000+200x or x = 15 Hence in year 2018 students reach 6000
B Regression C D. All the above.
This chapter discusses repetition and looping control structures in Java, including while, for, and do-while loops. It provides examples of using these loops, such as printing numbers in a range or calculating Fibonacci numbers recursively. The chapter also covers statements for early loop exit like break and continue, and nesting control structures for increased complexity.
The document discusses different types of loops in Java including while, do-while, for, nested, and loops using break and continue statements. It provides examples of a guessing game program using a do-while loop that repeatedly prompts the user for a guess and checks if it matches a random number. It also gives short code examples demonstrating the basic syntax of for, nested, and loops with break and continue.
This document provides an overview of loops in Java, including for, while, do-while loops as well as break and continue statements. It discusses using loops to iterate through arrays or to repeatedly execute blocks of code when the number of iterations is predictable or unpredictable. Examples are provided to calculate factorials using different loop types and to demonstrate the break and continue statements. Additional learning resources on Java programming concepts are also listed.
The document discusses various programming concepts in C# such as data types, control flow statements like if/else, switch, loops (for, while, do-while), methods for generating random numbers, and examples of programming problems involving calculations, patterns, and simulating dice rolls. Random numbers can be generated using the Random class, control structures conditionally execute blocks of code, and loops iterate code for a set number of repetitions.
This document discusses different types of loops in Java including while, do-while, and for loops. It explains the syntax and flow control of each loop type. Examples are provided to demonstrate how to use loops appropriately. Common mistakes like infinite loops and off-by-one errors are highlighted. The break and continue keywords are also explained. Finally, the document briefly introduces methods in Java.
The document discusses various programming concepts in C# such as random number generation, Boolean expressions, control statements like if/else, switch, for, while and do-while loops. It also covers nested loops, break and continue statements, and provides examples of problems that can be solved using these programming constructs like generating random numbers, printing patterns, and simulating dice rolls.
The document discusses different types of loops in Java including while, do-while, and for loops. It provides examples of using each loop type to repeatedly print a string, generate math quiz questions, and calculate a sum of user inputs. Key aspects covered include initializing and updating a loop counter, loop continuation conditions, and using loops with sentinel values to control the number of iterations.
The document discusses different types of repetition structures in Java programming such as while, for, and do-while loops. It provides examples of how to use each loop type and when each is best suited depending on whether the number of iterations is known. The document also covers break and continue statements that can be used to exit or skip iterations in loops.
The document discusses different types of repetition structures in Java programming such as while, for, and do-while loops. It covers how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled loops. Examples are provided to illustrate different types of loops and how to choose the appropriate one for a given programming problem.
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.
Which if statement below tests if letter holds R (letter is a char .pdfaniarihant
Which if statement below tests if letter holds R? (letter is a char variable)
if ( letter == \"R\")
if ( letter >= \'R\')
if ( letter == R)
if ( letter = \'R\')
if ( letter == \'R\')
What are if statements used for in programs?
Repeating commands
Storing data
Numeric calculations
Numeric casts
Making decisions
The following if statement tests the rainfall in New York’s Central Park during the months of
June, July and August.
if (low <= rain && rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
It could be replaced with:
I.
if (rain >= low)
{
if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
}
else
System.out.println(\"Rainfall amount is abnormal.\");
II.
if (rain >= low)
{
if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
}
else
System.out.println(\"Rainfall amount is abnormal.\");
III.
if (rain >= low)
System.out.println(\"Rainfall amount is normal.\");
else if (rain <= high)
System.out.println(\"Rainfall amount is normal.\");
else
System.out.println(\"Rainfall amount is abnormal.\");
I only
II only
III only
II or III
I, II or III
What is output by the following code?
int x = 36 % 8;
if (x >= 10)
System.out.println( 1);
else if (x >= 8)
System.out.println( 2);
else if (x >= 6)
System.out.println( 3);
else if ( x >= 4)
System.out.println( 4);
else
System.out.println( 5);
1
2
3
4
5
Consider the code:
if ( y == 0 || x * y > 10)
Which of the following is an example of short circuit evaluation?
if x * y > 10 is false it evaluates y ==0
if x * y > 10 is false it doesn\'t evaluate y ==0
if y == 0 is false it doesn\'t evaluate x * y > 10
if y == 0 is true it doesn\'t evaluate x * y > 10
if y == 0 is false it evaluates x * y > 10
The following truth table matches which boolean condition?
A && ( A || B)
A || ( !A && !B)
A && ( A && B)
!A && ( A || !B)
A || ( A || B)
Consider the code:
if (a < b && c != d)
Which of the following is an example of short circuit evaluation?
if a < b is true it doesn\'t evaluate c != d
if a < b is false it doesn\'t evaluate c != d
if c != d is false it evaluates a < b
if c != d is true it doesn\'t evaluate a < b
if a < b is true it evaluates c != d
! ( x < y && w == z) is the same as which boolean expression?
x <= y && w == z
x >= y || w != z
x <= y || w != z
x <= y && w != z
x < y && w != z
Assume that x and y are boolean variables and have been properly initialized.
!(x || y) || (x || y)
The result of evaluating the expression above is best described as:
always true
always false
true only when x is true and y is true
true only when x and y have the same value
true only when x and y have different values
What is output to the screen by the following code?
int c = 2;
while (c < 6)
{
System.out.print((int)Math.pow (-1, c)+\" \");
c++;
}
-1 1 -1 1 -1 1 -1
1 -1 1 -1
-1 1 -1 1 -1 1
1 1 1 1 1 1
-1 -1 -1 -1 -1 -1
How many times will the following loop repeat?.
The document discusses looping statements and examples of using while and for loops to repeatedly execute blocks of code. It provides examples of using loops to generate math quiz questions, guess random numbers, calculate sums, and find greatest common divisors. It also discusses using break and continue statements, nested loops, minimizing numerical errors, and Monte Carlo simulations.
This document contains code snippets and explanations related to Java programming concepts like classes, objects, methods, conditionals, loops, and arrays. It begins with simple examples of printing text and using methods. It then covers more complex topics like defining classes with fields and methods, if/else and switch conditional statements, for, while, and do-while loops, parsing user input, and creating and accessing objects. The document appears to be notes or exercises for learning Java programming fundamentals through worked examples and explanations.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This document appears to be an assignment submission for a post graduate diploma in information technology. It contains 10 questions related to Java programming and the answers/code snippets provided for each question. The questions cover topics like simple interest calculation, sum of digits, Fibonacci series, converting decimal to Roman numerals, prime numbers, nested for loops to print patterns, recursive factorial, defining custom exceptions and creating a simple welcome applet.
CMIS 102 Hands-On Lab
// Week 4
Overview:
This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, analysis, test plan, design (using both flow chart and pseudocode visualization), and implementation with C code. The example provided uses sequential, selection and repetition statements.
Program Description:
This program will calculate the sum of 10 integers. The program will ask the user to 10 integers. If the sum of the numbers is greater than 1000, a message is printed stating the sum is over 1000. The design step will include both pseudocode and flow chart visualization.
Analysis:
I will use sequential, selection and repetition programming statements.
I will define three integer numbers: count, value, sum. Count will store how many times values are entered to make sure we don’t exceed 10 values. Value will store the input integer and sum will store the running sum.
The sum will be calculated by this formula:
sum = sum + value
For example, if the first value entered was 4 and second was 10:
sum = sum + value = 0 + 4
sum = 4 + 10 = 14
Values and sum can be input and calculated within a repetition loop:
while count <10
Input value
sum = sum + value
End while
The additional selection statement will be of this form:
If sum > 1000 then
print "Sum is over 1000"
End If
Test Plan:
To verify this program is working properly the input values could be used for testing:
Test Case
Input
Expected Output
1
value=1
value=1
value=1
value=0
value=1
value=2
value=0
value=1
value=3
value=2
Sum = 12
2
value=100
value=100
value=100
value=100
value=100
value=200
value=200
value=200
value=200
value=200
Sum = 1200
Sum is over 1000.
3
value=-100
value=-100
value=-200
value=0
value=200
value=100
value=0
value=200
value=-300
value=-200
Sum = -400
Pseudocode:
// This program will calculate the sum of 10 integers.
// Declare variables
Declare count, value, sum as Integer
//Initialize Counter, Sum to 0
Set count=0
Set sum = 0
// Loop through 10 integers
While count < 10
Print “Enter an Integer”
Input value
sum = sum + value
count=count+1
End While
// Print results and messages
Print “Sum is “ + sum
If (sum > 1000)
Printf “Sum is over 1000”
End if
Flow Chart:
C Code
The following is the C Code that will compile in execute in the online compilers.
// C code
// This program will calculate the sum of 10 integers.
// Developer: Faculty CMIS102
// Date: Jan 31, 2014
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
/* Initialize count and sum */
count = 0;
sum = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter an Integer\n");
scanf("%d", &value);
sum = sum + value;
count = count + 1;
}
printf("Sum is %d\n " , sum );
if (sum >1000)
printf("Sum is over 1000\n");
return 0;
}
Setting up the code and the input parameters in ideone.com:
Note the input integer.
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
This document discusses file processing in Java. It covers topics like creating File objects, reading and writing files with Scanners and PrintWriters, handling exceptions when reading files, and processing file input line by line or token by token. Examples are provided to demonstrate reading numeric data from files and calculating values based on the data. The key aspects are using Scanners to read files, handling exceptions, and choosing between line-based and token-based processing depending on the file format.
This document discusses conditional execution and if/else statements in Java. It covers the basic if statement, if/else statement, relational operators, nested if/else structures, and misuse of if statements. It also discusses logical operators, evaluating logical expressions, factoring if/else code, methods that return values based on if/else conditions, and ensuring all code paths return a value. Finally, it discusses cumulative algorithms using if/else structures and loops to calculate running sums and products.
The document discusses object-oriented programming concepts like classes, objects, and methods. It provides examples of how classes act as blueprints for creating multiple objects that encapsulate both data (state) and behavior. Objects of the same class share the same methods but each object contains its own unique state data. The document uses iPods as an example - the iPod class acts as a blueprint, and individual iPod objects like iPod #1 contain their own song, volume, and battery life state details.
This document provides information about using graphics in Java, including:
- The DrawingPanel, Graphics, and Color objects used for drawing
- Common Graphics methods like drawLine, fillOval, setColor
- Coordinate system and drawing shapes at different positions
- Using loops and parameters to draw multiple shapes
- Creating simple animations using the DrawingPanel sleep method
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
This document provides an introduction to Java programming. It discusses what computer science and programming are, and introduces basic Java concepts like classes, methods, and print statements. It also covers data types, variables, operators, and control structures that allow programmers to write algorithms and programs. The document uses examples like simple print programs and a cookie baking algorithm to demonstrate core Java programming concepts.
This document discusses the concept of the "myth of the lazy native" which was used during colonial times to justify European domination over Southeast Asian societies. It analyzes how this myth functioned as part of the colonial ideology and distorted the realities of indigenous societies. The introduction defines key terms like ideology and colonial capitalism used in the analysis. It notes how colonial capitalism differed from historical capitalism in Western Europe in its lack of free labor, minimal industrial development, and dualistic social structures in colonized societies.
Build enterprise-ready applications using skills you already have!PhilMeredith3
Process Tempo is a rapid application development (RAD) environment that empowers data teams to create enterprise-ready applications using skills they already have.
With Process Tempo, data teams can craft beautiful, pixel-perfect applications the business will love.
Process Tempo combines features found in business intelligence tools, graphic design tools and workflow solutions - all in a single platform.
Process Tempo works with all major databases such as Databricks, Snowflake, Postgres and MySQL. It also works with leading graph database technologies such as Neo4j, Puppy Graph and Memgraph.
It is the perfect platform to accelerate the delivery of data-driven solutions.
For more information, you can find us at www.processtempo.com
Design by Contract - Building Robust Software with Contract-First DevelopmentPar-Tec S.p.A.
In the fast-paced world of software development, code quality and reliability are paramount. This SlideShare deck, presented at PyCon Italia 2025 by Antonio Spadaro, DevOps Engineer at Par-Tec, introduces the “Design by Contract” (DbC) philosophy and demonstrates how a Contract-First Development approach can elevate your projects.
Beginning with core DbC principles—preconditions, postconditions, and invariants—these slides define how formal “contracts” between classes and components lead to clearer, more maintainable code. You’ll explore:
The fundamental concepts of Design by Contract and why they matter.
How to write and enforce interface contracts to catch errors early.
Real-world examples showcasing how Contract-First Development improves error handling, documentation, and testability.
Practical Python demonstrations using libraries and tools that streamline DbC adoption in your workflow.
Secure and Simplify IT Management with ManageEngine Endpoint Central.pdfNorthwind Technologies
ManageEngine Endpoint Central (formerly known as Desktop Central) is an all-in-one endpoint management solution designed for managing a diverse and distributed IT environment. It supports Windows, macOS, Linux, iOS, Android, and Chrome OS devices, offering a centralized approach to managing endpoints — whether they’re on-premise, remote, or hybrid.
The rise of e-commerce has redefined how retailers operate—and reconciliation...Prachi Desai
As payment flows grow more fragmented, the complexity of reconciliation and revenue recognition increases. The result? Mounting operational costs, silent revenue leakages, and avoidable financial risk.
Spot the inefficiencies. Automate what’s slowing you down.
https://www.taxilla.com/ecommerce-reconciliation
Custom Software Development: Types, Applications and Benefits.pdfDigital Aptech
Discover the different types of custom software, their real-world applications across industries, and the key benefits they offer. Learn how tailored solutions improve efficiency, scalability, and business performance in this comprehensive overview.
Agentic AI Desgin Principles in five slides.pptxMOSIUOA WESI
Discover the core design patterns that enable AI agents to think, learn, and collaborate like never before. From breaking down goals to coordinating across systems, these patterns form the foundation of advanced intelligent behavior. Learn how reinforcement learning, hierarchical planning, and multi-agent systems are transforming AI capabilities. This presentation offers a concise yet powerful overview of agentic design in action. Perfect for developers, researchers, and AI enthusiasts ready to build smarter systems.
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffTier1 app
When it comes to performance testing, most engineers instinctively gravitate toward the big-picture indicators—response time, memory usage, throughput. But what about the smaller, more subtle indicators that quietly shape your application’s performance and stability? we explored the hidden layer of performance diagnostics that too often gets overlooked: micro-metrics. These small but mighty data points can reveal early signs of trouble long before they manifest as outages or degradation in production.
From garbage collection behavior and object creation rates to thread state transitions and blocked thread patterns, we unpacked the critical micro-metrics every performance engineer should assess before giving the green light to any release.
This session went beyond the basics, offering hands-on demonstrations and JVM-level diagnostics that help identify performance blind spots traditional tests tend to miss. We showed how early detection of these subtle anomalies can drastically reduce post-deployment issues and production firefighting.
Whether you're a performance testing veteran or new to JVM tuning, this session helped shift your validation strategies left—empowering you to detect and resolve risks earlier in the lifecycle.
Online Queue Management System for Public Service Offices [Focused on Municip...Rishab Acharya
This report documents the design and development of an Online Queue Management System tailored specifically for municipal offices in Nepal. Municipal offices, as critical providers of essential public services, face challenges including overcrowded queues, long waiting times, and inefficient service delivery, causing inconvenience to citizens and pressure on municipal staff. The proposed digital platform allows citizens to book queue tokens online for various physical services, facilitating efficient queue management and real-time wait time updates. Beyond queue management, the system includes modules to oversee non-physical developmental programs, such as educational and social welfare initiatives, enabling better participation and progress monitoring. Furthermore, it incorporates a module for monitoring infrastructure development projects, promoting transparency and allowing citizens to report issues and track progress. The system development follows established software engineering methodologies, including requirement analysis, UML-based system design, and iterative testing. Emphasis has been placed on user-friendliness, security, and scalability to meet the diverse needs of municipal offices across Nepal. Implementation of this integrated digital platform will enhance service efficiency, increase transparency, and improve citizen satisfaction, thereby supporting the modernization and digital transformation of public service delivery in Nepal.
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfQuickBooks Training
Are you preparing your budget for the next year, applying for a business credit card or loan, or opening a company bank account? If so, you may find QuickBooks financial statements to be a very useful tool.
These statements offer a brief, well-structured overview of your company’s finances, facilitating goal-setting and money management.
Don’t worry if you’re not knowledgeable about QuickBooks financial statements. These statements are complete reports from QuickBooks that provide an overview of your company’s financial procedures.
They thoroughly view your financial situation by including important features: income, expenses, investments, and disadvantages. QuickBooks financial statements facilitate your financial management and assist you in making wise determinations, regardless of your experience as a business owner.
Delivering More with Less: AI Driven Resource Management with OnePlan OnePlan Solutions
Delivering more with less is an age-old problem. Smaller budgets, leaner teams, and greater uncertainty make the path to success unclear. Combat these issues with confidence by leveraging the best practices that help PMOs balance workloads, predict bottlenecks, and ensure resources are deployed effectively, using OnePlan’s AI forecasting capabilities, especially when organizations must deliver more with fewer people.
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIUdit Goenka
1billion people scroll, only 1 % post…
That’s your opening to hijack LinkedIn—and Autoposting.ai is the unfair weapon Slideshare readers are hunting for…
LinkedIn drives 80 % of social B2B leads, converts 2× better than every other network, yet 87 % of pros still choke on the content hamster-wheel…
They burn 25 h a month writing beige posts, miss hot trends, then watch rivals scoop the deals…
Enter Autoposting.ai, the first agentic-AI engine built only for LinkedIn domination…
It spies on fresh feed data, cracks trending angles before they peak, and spins voice-perfect thought-leadership that sounds like you—not a robot…
Slides in play:
• 78 % average engagement lift in 90 days…
• 3.2× qualified-lead surge over manual posting…
• 42 % marketing time clawed back, week after week…
Real users report 5-8× ROI inside the first quarter, some crossing $1 M ARR six months faster…
Why does it hit harder than Taplio, Supergrow, generic AI writers?
• Taplio locks key features behind $149+ tiers… Autoposting gives you everything at $29…
• Supergrow churns at 20 % because “everyone” is no-one… Autoposting laser-targets • • LinkedIn’s gold-vein ICPs and keeps them glued…
• ChatGPT needs prompts, edits, scheduling hacks… Autoposting researches, writes, schedules—and optimizes send-time in one sweep…
Need social proof?
G2 reviews scream “game-changer”… Agencies slash content production 80 % and triple client capacity… CXOs snag PR invites and investor DMs after a single week of daily posts… Employee advocates hit 8× reach versus company pages and pump 25 % more SQLs into the funnel…
Feature bullets for the skim-reader:
• Agentic Research Engine—tracks 27+ data points, finds gaps your rivals ignore…
• Real Voice Match—your tone, slang, micro-jokes, intact…
• One-click Multiplatform—echo winning posts to Twitter, Insta, Facebook…
• Team Workspaces—spin up 10 seats without enterprise red tape…
• AI Timing—drops content when your buyers actually scroll, boosting first-hour velocity by up to 4×…
Risk? Zero…
Free 7-day trial, 90-day results guarantee—hit 300 % ROI or walk away… but the clock is ticking while competitors scoop your feed…
So here’s the ask:
Swipe down, smash the “Download” or “Try Now” button, and let Autoposting.ai turn Slideshare insights into pipeline—before today’s trending topic vanishes…
The window is open… How loud do you want your LinkedIn megaphone?
Explore the professional resume of Pramod Kumar, a skilled iOS developer with extensive experience in Swift, SwiftUI, and mobile app development. This portfolio highlights key projects, technical skills, and achievements in app design and development, showcasing expertise in creating intuitive, high-performance iOS applications. Ideal for recruiters and tech managers seeking a talented iOS engineer for their team.
In today’s workplace, staying connected is more important than ever. Whether teams are remote, hybrid, or back in the office, communication and collaboration are at the heart of getting things done. But here’s the truth — outdated intranets just don’t cut it anymore.
Content Mate Web App Triples Content Managers‘ ProductivityAlex Vladimirovich
Content Mate is a web application that consolidates dozens of fragmented operations into a single interface. The input is a list of product SKUs, and the output is an archive containing processed images, PDF documents, and spreadsheets with product names, descriptions, attributes, and key features—ready for bulk upload.
2. 2
A deceptive problem...
• Write a method printNumbers that prints each number from
1 to a given maximum, separated by commas.
For example, the call:
printNumbers(5)
should print:
1, 2, 3, 4, 5
3. 3
Flawed solutions
• public static void printNumbers(int max) {
for (int i = 1; i <= max; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line of output
}
– Output from printNumbers(5): 1, 2, 3, 4, 5,
• public static void printNumbers(int max) {
for (int i = 1; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line of output
}
– Output from printNumbers(5): , 1, 2, 3, 4, 5
4. 4
Fence post analogy
• We print n numbers but need only n - 1 commas.
• Similar to building a fence with wires separated by posts:
– If we use a flawed algorithm that repeatedly places a post + wire,
the last post will have an extra dangling wire.
for (length of fence) {
place a post.
place some wire.
}
5. 5
Fencepost loop
• Add a statement outside the loop to place the initial "post."
– Also called a fencepost loop or a "loop-and-a-half" solution.
place a post.
for (length of fence - 1) {
place some wire.
place a post.
}
6. 6
Fencepost method solution
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}
• Alternate solution: Either first or last "post" can be taken out:
public static void printNumbers(int max) {
for (int i = 1; i <= max - 1; i++) {
System.out.print(i + ", ");
}
System.out.println(max); // to end the line
}
7. 7
Fencepost question
• Modify your method printNumbers into a new method
printPrimes that prints all prime numbers up to a max.
– Example: printPrimes(50) prints
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47
– If the maximum is less than 2, print no output.
• To help you, write a method countFactors which returns the
number of factors of a given integer.
– countFactors(20) returns 6 due to factors 1, 2, 4, 5, 10, 20.
8. 8
Fencepost answer
// Prints all prime numbers up to the given max.
public static void printPrimes(int max) {
if (max >= 2) {
System.out.print("2");
for (int i = 3; i <= max; i++) {
if (countFactors(i) == 2) {
System.out.print(", " + i);
}
}
System.out.println();
}
}
// Returns how many factors the given number has.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of number
}
}
return count;
}
10. 10
Categories of loops
• definite loop: Executes a known number of times.
– The for loops we have seen are definite loops.
• Print "hello" 10 times.
• Find all the prime numbers up to an integer n.
• Print each odd number between 5 and 127.
• indefinite loop: One where the number of times its body
repeats is not known in advance.
• Prompt the user until they type a non-negative number.
• Print random numbers until a prime number is printed.
• Repeat until the user has types "q" to quit.
11. 11
The while loop
• while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}
• Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
// output: 1 2 4 8 16 32 64 128
12. 12
Example while loop
// finds the first factor of 91, other than 1
int n = 91;
int factor = 2;
while (n % factor != 0) {
factor++;
}
System.out.println("First factor is " + factor);
// output: First factor is 7
– while is better than for because we don't know how many
times we will need to increment to find the factor.
13. 13
• sentinel: A value that signals the end of user input.
– sentinel loop: Repeats until a sentinel value is seen.
• Example: Write a program that prompts the user for numbers
until the user types 0, then outputs their sum.
– (In this case, 0 is the sentinel value.)
Enter a number (0 to quit): 10
Enter a number (0 to quit): 20
Enter a number (0 to quit): 30
Enter a number (0 to quit): 0
The sum is 60
Sentinel values
14. 14
Flawed sentinel solution
• What's wrong with this solution?
Scanner console = new Scanner(System.in);
int sum = 0;
int number = 1; // "dummy value", anything but 0
while (number != 0) {
System.out.print("Enter a number (0 to quit): ");
number = console.nextInt();
sum = sum + number;
}
System.out.println("The total is " + sum);
15. 15
Changing the sentinel value
• Modify your program to use a sentinel value of -1.
– Example log of execution:
Enter a number (-1 to quit): 15
Enter a number (-1 to quit): 25
Enter a number (-1 to quit): 10
Enter a number (-1 to quit): 30
Enter a number (-1 to quit): -1
The total is 80
16. 16
Changing the sentinel value
• To see the problem, change the sentinel's value to -1:
Scanner console = new Scanner(System.in);
int sum = 0;
int number = 1; // "dummy value", anything but -1
while (number != -1) {
System.out.print("Enter a number (-1 to quit): ");
number = console.nextInt();
sum = sum + number;
}
System.out.println("The total is " + sum);
• Now the solution produces the wrong output. Why?
The total was 79
17. 17
The problem with our code
• Our code uses a pattern like this:
sum = 0.
while (input is not the sentinel) {
prompt for input; read input.
add input to the sum.
}
• On the last pass, the sentinel -1 is added to the sum:
prompt for input; read input (-1).
add input (-1) to the sum.
• This is a fencepost problem.
– Must read N numbers, but only sum the first N-1 of them.
18. 18
A fencepost solution
sum = 0.
prompt for input; read input. // place a "post"
while (input is not the sentinel) {
add input to the sum. // place a "wire"
prompt for input; read input. // place a "post"
}
• Sentinel loops often utilize a fencepost "loop-and-a-half" style
solution by pulling some code out of the loop.
19. 19
Correct sentinel code
Scanner console = new Scanner(System.in);
int sum = 0;
// pull one prompt/read ("post") out of the loop
System.out.print("Enter a number (-1 to quit): ");
int number = console.nextInt();
while (number != -1) {
sum = sum + number; // moved to top of loop
System.out.print("Enter a number (-1 to quit): ");
number = console.nextInt();
}
System.out.println("The total is " + sum);
20. 20
Sentinel as a constant
public static final int SENTINEL = -1;
...
Scanner console = new Scanner(System.in);
int sum = 0;
// pull one prompt/read ("post") out of the loop
System.out.print("Enter a number (" + SENTINEL +
" to quit): ");
int number = console.nextInt();
while (number != SENTINEL) {
sum = sum + number; // moved to top of loop
System.out.print("Enter a number (" + SENTINEL +
" to quit): ");
number = console.nextInt();
}
System.out.println("The total is " + sum);
22. 22
The Random class
• A Random object generates pseudo-random numbers.
– Class Random is found in the java.util package.
import java.util.*;
– Example:
Random rand = new Random();
int randomNumber = rand.nextInt(10); // 0-9
Method name Description
nextInt() returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble() returns a random real number in the range [0.0, 1.0)
23. 23
Generating random numbers
• Common usage: to get a random number from 1 to N
int n = rand.nextInt(20) + 1; // 1-20 inclusive
• To get a number in arbitrary range [min, max] inclusive:
name.nextInt(size of range) + min
• where (size of range) is (max - min + 1)
– Example: A random integer between 4 and 10 inclusive:
int n = rand.nextInt(7) + 4;
24. 24
Random questions
• Given the following declaration, how would you get:
Random rand = new Random();
– A random number between 1 and 47 inclusive?
int random1 = rand.nextInt(47) + 1;
– A random number between 23 and 30 inclusive?
int random2 = rand.nextInt(8) + 23;
– A random even number between 4 and 12 inclusive?
int random3 = rand.nextInt(5) * 2 + 4;
25. 25
Random and other types
• nextDouble method returns a double between 0.0 - 1.0
– Example: Get a random GPA value between 1.5 and 4.0:
double randomGpa = rand.nextDouble() * 2.5 + 1.5;
• Any set of possible values can be mapped to integers
– code to randomly play Rock-Paper-Scissors:
int r = rand.nextInt(3);
if (r == 0) {
System.out.println("Rock");
} else if (r == 1) {
System.out.println("Paper");
} else { // r == 2
System.out.println("Scissors");
}
26. 26
Random question
• Write a program that simulates rolling of two 6-sided dice until
their combined result comes up as 7.
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!
27. 27
Random answer
// Rolls two dice until a sum of 7 is reached.
import java.util.*;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
System.out.println("You won after " + tries + " tries!");
}
}
28. 28
Random question
• Write a program that plays an adding game.
– Ask user to solve random adding problems with 2-5 numbers.
– The user gets 1 point for a correct answer, 0 for incorrect.
– The program stops after 3 incorrect answers.
4 + 10 + 3 + 10 = 27
9 + 2 = 11
8 + 6 + 7 + 9 = 25
Wrong! The answer was 30
5 + 9 = 13
Wrong! The answer was 14
4 + 9 + 9 = 22
3 + 1 + 7 + 2 = 13
4 + 2 + 10 + 9 + 7 = 42
Wrong! The answer was 32
You earned 4 total points.
29. 29
Random answer
// Asks the user to do adding problems and scores them.
import java.util.*;
public class AddingGame {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random rand = new Random();
// play until user gets 3 wrong
int points = 0;
int wrong = 0;
while (wrong < 3) {
int result = play(console, rand); // play one game
if (result > 0) {
points++;
} else {
wrong++;
}
}
System.out.println("You earned " + points + " total points.");
}
30. 30
Random answer 2
...
// Builds one addition problem and presents it to the user.
// Returns 1 point if you get it right, 0 if wrong.
public static int play(Scanner console, Random rand) {
// print the operands being added, and sum them
int operands = rand.nextInt(4) + 2;
int sum = rand.nextInt(10) + 1;
System.out.print(sum);
for (int i = 2; i <= operands; i++) {
int n = rand.nextInt(10) + 1;
sum += n;
System.out.print(" + " + n);
}
System.out.print(" = ");
// read user's guess and report whether it was correct
int guess = console.nextInt();
if (guess == sum) {
return 1;
} else {
System.out.println("Wrong! The answer was " + total);
return 0;
}
}
}
31. 31
The do/while loop
• do/while loop: Performs its test at the end of each repetition.
– Guarantees that the loop's {} body will run at least once.
do {
statement(s);
} while (test);
// Example: prompt until correct password is typed
String phrase;
do {
System.out.print("Type your password: ");
phrase = console.next();
} while (!phrase.equals("abracadabra"));
32. 32
do/while question
• Modify the previous Dice program to use do/while.
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!
• Is do/while a good fit for our past Sentinel program?
33. 33
do/while answer
// Rolls two dice until a sum of 7 is reached.
import java.util.*;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum;
do {
int roll1 = rand.nextInt(6) + 1; // one roll
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
} while (sum != 7);
System.out.println("You won after " + tries + " tries!");
}
}
35. 35
Methods that are tests
• Some methods return logical values.
– A call to such a method is used as a test in a loop or if.
Scanner console = new Scanner(System.in);
System.out.print("Type your first name: ");
String name = console.next();
if (name.startsWith("Dr.")) {
System.out.println("Will you marry me?");
} else if (name.endsWith("Esq.")) {
System.out.println("And I am Ted 'Theodore' Logan!");
}
36. 36
String test methods
String name = console.next();
if (name.contains("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase("STUART")) {
System.out.println("Let's talk about meta!");
}
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
37. 37
Type boolean
• boolean: A logical type whose values are true and false.
– A logical test is actually a boolean expression.
– It is legal to:
• create a boolean variable
• pass a boolean value as a parameter
• return a boolean value from methods
• call a method that returns a boolean and use it as a test
boolean minor = (age < 21);
boolean isProf = name.contains("Prof");
boolean lovesCSE = true;
// allow only CSE-loving students over 21
if (minor || isProf || !lovesCSE) {
System.out.println("Can't enter the club!");
}
38. 38
Using boolean
• Why is type boolean useful?
– Can capture a complex logical test result and use it later
– Can write a method that does a complex test and returns it
– Makes code more readable
– Can pass around the result of a logical test (as param/return)
boolean goodAge = age >= 12 && age < 29;
boolean goodHeight = height >= 78 && height < 84;
boolean rich = salary >= 100000.0;
if ((goodAge && goodHeight) || rich) {
System.out.println("Okay, let's go out!");
} else {
System.out.println("It's not you, it's me...");
}
39. 39
Returning boolean
public static boolean isPrime(int n) {
int factors = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
factors++;
}
}
if (factors == 2) {
return true;
} else {
return false;
}
}
• Calls to methods returning boolean can be used as tests:
if (isPrime(57)) {
...
}
40. 40
Boolean question
• Improve our "rhyme" / "alliterate" program to use boolean
methods to test for rhyming and alliteration.
Type two words: Bare blare
They rhyme!
They alliterate!
41. 41
Boolean answer
if (rhyme(word1, word2)) {
System.out.println("They rhyme!");
}
if (alliterate(word1, word2)) {
System.out.println("They alliterate!");
}
...
// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
if (s2.length() >= 2 && s1.endsWith(s2.substring(s2.length() - 2))) {
return true;
} else {
return false;
}
}
// Returns true if s1 and s2 start with the same letter.
public static boolean alliterate(String s1, String s2) {
if (s1.startsWith(s2.substring(0, 1))) {
return true;
} else {
return false;
}
}
42. 42
"Boolean Zen", part 1
• Students new to boolean often test if a result is true:
if (isPrime(57) == true) { // bad
...
}
• But this is unnecessary and redundant. Preferred:
if (isPrime(57)) { // good
...
}
• A similar pattern can be used for a false test:
if (isPrime(57) == false) { // bad
if (!isPrime(57)) { // good
43. 43
"Boolean Zen", part 2
• Methods that return boolean often have an
if/else that returns true or false:
public static boolean bothOdd(int n1, int n2) {
if (n1 % 2 != 0 && n2 % 2 != 0) {
return true;
} else {
return false;
}
}
– But the code above is unnecessarily verbose.
44. 44
Solution w/ boolean var
• We could store the result of the logical test.
public static boolean bothOdd(int n1, int n2) {
boolean test = (n1 % 2 != 0 && n2 % 2 != 0);
if (test) { // test == true
return true;
} else { // test == false
return false;
}
}
– Notice: Whatever test is, we want to return that.
• If test is true , we want to return true.
• If test is false, we want to return false.
45. 45
Solution w/ "Boolean Zen"
• Observation: The if/else is unnecessary.
– The variable test stores a boolean value;
its value is exactly what you want to return. So return that!
public static boolean bothOdd(int n1, int n2) {
boolean test = (n1 % 2 != 0 && n2 % 2 != 0);
return test;
}
• An even shorter version:
– We don't even need the variable test.
We can just perform the test and return its result in one step.
public static boolean bothOdd(int n1, int n2) {
return (n1 % 2 != 0 && n2 % 2 != 0);
}
46. 46
"Boolean Zen" template
• Replace
public static boolean name(parameters) {
if (test) {
return true;
} else {
return false;
}
}
• with
public static boolean name(parameters) {
return test;
}
47. 47
Improved isPrime method
• The following version utilizes Boolean Zen:
public static boolean isPrime(int n) {
int factors = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
factors++;
}
}
return factors == 2; // if n has 2 factors, true
}
• Modify our Rhyme program to use Boolean Zen.
48. 48
Boolean Zen answer
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type two words: ");
String word1 = console.next().toLowerCase();
String word2 = console.next().toLowerCase();
if (rhyme(word1, word2)) {
System.out.println("They rhyme!");
}
if (alliterate(word1, word2)) {
System.out.println("They alliterate!");
}
}
// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
return s2.length() >= 2 && s1.endsWith(s2.substring(s2.length() - 2));
}
// Returns true if s1 and s2 start with the same letter.
public static boolean alliterate(String s1, String s2) {
return s1.startsWith(s2.substring(0, 1));
}
49. 49
"Short-circuit" evaluation
• Java stops evaluating a test if it knows the answer.
– && stops early if any part of the test is false
– || stops early if any part of the test is true
• The following test will crash if s2's length is less than 2:
// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
return s1.endsWith(s2.substring(s2.length() - 2)) &&
s1.length() >= 2 && s2.length() >= 2;
}
• The following test will not crash; it stops if length < 2:
// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
return s1.length() >= 2 && s2.length() >= 2 &&
s1.endsWith(s2.substring(s2.length() - 2));
}
50. 50
De Morgan's Law
• De Morgan's Law: Rules used to negate boolean tests.
– Useful when you want the opposite of an existing test.
– Example:
Original Expression Negated Expression Alternative
a && b !a || !b !(a && b)
a || b !a && !b !(a || b)
Original Code Negated Code
if (x == 7 && y > 3) {
...
}
if (x != 7 || y <= 3) {
...
}
51. 51
Boolean practice questions
• Write a method named isVowel that returns whether a
String is a vowel (a, e, i, o, or u), case-insensitively.
– isVowel("q") returns false
– isVowel("A") returns true
– isVowel("e") returns true
• Change the above method into an isNonVowel that returns
whether a String is any character except a vowel.
– isNonVowel("q") returns true
– isNonVowel("A") returns false
– isNonVowel("e") returns false
52. 52
Boolean practice answers
// Enlightened version. I have seen the true way (and false way)
public static boolean isVowel(String s) {
return s.equalsIgnoreCase("a") || s.equalsIgnoreCase("e") ||
s.equalsIgnoreCase("i") || s.equalsIgnoreCase("o") ||
s.equalsIgnoreCase("u");
}
// Enlightened "Boolean Zen" version
public static boolean isNonVowel(String s) {
return !s.equalsIgnoreCase("a") && !s.equalsIgnoreCase("e") &&
!s.equalsIgnoreCase("i") && !s.equalsIgnoreCase("o") &&
!s.equalsIgnoreCase("u");
// or, return !isVowel(s);
}
53. 53
When to return?
• Methods with loops and return values can be tricky.
– When and where should the method return its result?
• Write a method seven that accepts a Random parameter and
uses it to draw up to ten lotto numbers from 1-30.
– If any of the numbers is a lucky 7, the method should stop and
return true. If none of the ten are 7 it should return false.
– The method should print each number as it is drawn.
15 29 18 29 11 3 30 17 19 22 (first call)
29 5 29 4 7 (second call)
54. 54
Flawed solution
// Draws 10 lotto numbers; returns true if one is 7.
public static boolean seven(Random rand) {
for (int i = 1; i <= 10; i++) {
int num = rand.nextInt(30) + 1;
System.out.print(num + " ");
if (num == 7) {
return true;
} else {
return false;
}
}
}
– The method always returns immediately after the first roll.
– This is wrong if that roll isn't a 7; we need to keep rolling.
55. 55
Returning at the right time
// Draws 10 lotto numbers; returns true if one is 7.
public static boolean seven(Random rand) {
for (int i = 1; i <= 10; i++) {
int num = rand.nextInt(30) + 1;
System.out.print(num + " ");
if (num == 7) { // found lucky 7; can exit now
return true;
}
}
return false; // if we get here, there was no 7
}
– Returns true immediately if 7 is found.
– If 7 isn't found, the loop continues drawing lotto numbers.
– If all ten aren't 7, the loop ends and we return false.
56. 56
while loop question
• Write a method digitSum that accepts an integer parameter
and returns the sum of its digits.
– Assume that the number is non-negative.
– Example: digitSum(29107) returns 2+9+1+0+7 or 19
– Hint: Use the % operator to extract a digit from a number.
57. 57
while loop answer
public static int digitSum(int n) {
n = Math.abs(n); // handle negatives
int sum = 0;
while (n > 0) {
sum = sum + (n % 10); // add last digit
n = n / 10; // remove last digit
}
return sum;
}
58. 58
Boolean return questions
• hasAnOddDigit : returns true if any digit of an integer is odd.
– hasAnOddDigit(4822116) returns true
– hasAnOddDigit(2448) returns false
• allDigitsOdd : returns true if every digit of an integer is odd.
– allDigitsOdd(135319) returns true
– allDigitsOdd(9174529) returns false
• isAllVowels : returns true if every char in a String is a vowel.
– isAllVowels("eIeIo") returns true
– isAllVowels("oink") returns false
• These problems are available in our Practice-It! system under 5.x.
59. 59
Boolean return answers
public static boolean hasAnOddDigit(int n) {
while (n != 0) {
if (n % 2 != 0) { // check whether last digit is odd
return true;
}
n = n / 10;
}
return false;
}
public static boolean allDigitsOdd(int n) {
while (n != 0) {
if (n % 2 == 0) { // check whether last digit is even
return false;
}
n = n / 10;
}
return true;
}
public static boolean isAllVowels(String s) {
for (int i = 0; i < s.length(); i++) {
String letter = s.substring(i, i + 1);
if (!isVowel(letter)) {
return false;
}
}
return true;
}
61. 61
Logical assertions
• assertion: A statement that is either true or false.
Examples:
– Java was created in 1995.
– The sky is purple.
– 23 is a prime number.
– 10 is greater than 20.
– x divided by 2 equals 7. (depends on the value of x)
• An assertion might be false ("The sky is purple" above), but it
is still an assertion because it is a true/false statement.
62. 62
Reasoning about assertions
• Suppose you have the following code:
if (x > 3) {
// Point A
x--;
} else {
// Point B
x++;
// Point C
}
// Point D
• What do you know about x's value at the three points?
– Is x > 3? Always? Sometimes? Never?
63. 63
Assertions in code
• We can make assertions about our code and ask whether they are
true at various points in the code.
– Valid answers are ALWAYS, NEVER, or SOMETIMES.
System.out.print("Type a nonnegative number: ");
double number = console.nextDouble();
// Point A: is number < 0.0 here?
while (number < 0.0) {
// Point B: is number < 0.0 here?
System.out.print("Negative; try again: ");
number = console.nextDouble();
// Point C: is number < 0.0 here?
}
// Point D: is number < 0.0 here?
(SOMETIMES)
(ALWAYS)
(SOMETIMES)
(NEVER)
64. 64
Reasoning about assertions
• Right after a variable is initialized, its value is known:
int x = 3;
// is x > 0? ALWAYS
• In general you know nothing about parameters' values:
public static void mystery(int a, int b) {
// is a == 10? SOMETIMES
• But inside an if, while, etc., you may know something:
public static void mystery(int a, int b) {
if (a < 0) {
// is a == 10? NEVER
...
}
}
65. 65
Assertions and loops
• At the start of a loop's body, the loop's test must be true:
while (y < 10) {
// is y < 10? ALWAYS
...
}
• After a loop, the loop's test must be false:
while (y < 10) {
...
}
// is y < 10? NEVER
• Inside a loop's body, the loop's test may become false:
while (y < 10) {
y++;
// is y < 10? SOMETIMES
}
66. 66
"Sometimes"
• Things that cause a variable's value to be unknown
(often leads to "sometimes" answers):
– reading from a Scanner
– reading a number from a Random object
– a parameter's initial value to a method
• If you can reach a part of the program both with the answer
being "yes" and the answer being "no", then the correct
answer is "sometimes".
– If you're unsure, "Sometimes" is a good guess.
67. 67
Assertion example 1
public static void mystery(int x, int y) {
int z = 0;
// Point A
while (x >= y) {
// Point B
x = x - y;
z++;
if (x != y) {
// Point C
z = z * 2;
}
// Point D
}
// Point E
System.out.println(z);
}
x < y x == y z == 0
Point A
Point B
Point C
Point D
Point E
SOMETIMES SOMETIMES ALWAYS
NEVER SOMETIMES SOMETIMES
SOMETIMES NEVER NEVER
SOMETIMES SOMETIMES NEVER
ALWAYS NEVER SOMETIMES
Which of the following assertions are
true at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
68. 68
Assertion example 2
public static int mystery(Scanner console) {
int prev = 0;
int count = 0;
int next = console.nextInt();
// Point A
while (next != 0) {
// Point B
if (next == prev) {
// Point C
count++;
}
prev = next;
next = console.nextInt();
// Point D
}
// Point E
return count;
}
next == 0 prev == 0 next == prev
Point A
Point B
Point C
Point D
Point E
SOMETIMES ALWAYS SOMETIMES
NEVER SOMETIMES SOMETIMES
NEVER NEVER ALWAYS
SOMETIMES NEVER SOMETIMES
ALWAYS SOMETIMES SOMETIMES
Which of the following assertions are
true at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
69. 69
Assertion example 3
// Assumes y >= 0, and returns x^y
public static int pow(int x, int y) {
int prod = 1;
// Point A
while (y > 0) {
// Point B
if (y % 2 == 0) {
// Point C
x = x * x;
y = y / 2;
// Point D
} else {
// Point E
prod = prod * x;
y--;
// Point F
}
}
// Point G
return prod;
}
y > 0 y % 2 == 0
Point A
Point B
Point C
Point D
Point E
Point F
Point G
Which of the following assertions are
true at which point(s) in the code?
Choose ALWAYS, NEVER, or SOMETIMES.
y > 0 y % 2 == 0
Point A SOMETIMES SOMETIMES
Point B ALWAYS SOMETIMES
Point C ALWAYS ALWAYS
Point D ALWAYS SOMETIMES
Point E ALWAYS NEVER
Point F SOMETIMES ALWAYS
Point G NEVER ALWAYS