This document discusses program correctness and efficiency. It covers categories of program errors like syntax errors, semantic errors, and runtime errors. It discusses exceptions, the exception hierarchy, and how to catch and throw exceptions. It also discusses testing strategies like unit testing and black box testing. It provides tips for testing like developing test data, testing boundary conditions, using stubs and drivers, and performing regression testing. The overall goal is to discuss how to write correct and efficient programs through techniques like exception handling, testing, and analyzing algorithm efficiency.
The document provides an overview of exceptions in Java. It defines errors and exceptions, describes different types of exceptions including checked and unchecked exceptions, and explains key exception handling keywords like try, catch, throw, throws, and finally. The document aims to help programmers better understand exceptions and how to properly handle errors in their Java code.
This document provides an introduction to Java exceptions. It discusses what exceptions are, how they are handled using try/catch blocks, and the different types of exceptions including checked, unchecked, and user-defined exceptions. It also covers exception handling best practices such as only catching exceptions where they can be meaningfully handled, using the finally block to close resources, and avoiding empty catch blocks.
Exception handling in Java allows programs to deal with errors and unexpected conditions gracefully. The try block encloses code that might throw exceptions. When an exception is thrown, the runtime system searches the call stack for a catch block that can handle the exception. The finally block always executes after the try and catch blocks complete to ensure cleanup code runs. Custom exceptions can be created by extending the Exception class.
Exception handling in C++ provides a standard mechanism for processing errors. Exceptions indicate problems during a program's execution and exception handling allows a program to continue running or notify the user of problems. The key components are try blocks for code that could cause exceptions, catch handlers to handle specific exceptions, and stack unwinding to search for exception handlers up the call stack if an exception is not caught. Derived exception classes enable related errors to be caught together under a base class.
This document provides an overview of exception handling in Java. It defines exceptions as events that disrupt normal program flow and discusses different types of exceptions including checked exceptions that must be handled and unchecked exceptions that do not require handling. It also covers how to declare, throw, and catch exceptions in code as well as best practices for logging exceptions. Finally, it summarizes exception handling in WebSphere Commerce, including application-specific and system exceptions.
This document discusses exception handling in .NET. It defines what exceptions are, how they are handled using try, catch, and finally blocks, and common exception types in .NET. The main points covered are:
- Exceptions are events that disrupt normal program flow due to errors.
- try and catch blocks allow handling exceptions, while finally ensures cleanup code runs.
- Common .NET exceptions inherit from System.Exception.
- Exceptions simplify error handling and make applications more robust.
The document provides an overview of exceptions in Java. It defines errors and exceptions, describes different types of exceptions including checked and unchecked exceptions, and explains key exception handling keywords like try, catch, throw, throws, and finally. The document aims to help programmers better understand exceptions and how to properly handle errors in their Java code.
This document provides an introduction to Java exceptions. It discusses what exceptions are, how they are handled using try/catch blocks, and the different types of exceptions including checked, unchecked, and user-defined exceptions. It also covers exception handling best practices such as only catching exceptions where they can be meaningfully handled, using the finally block to close resources, and avoiding empty catch blocks.
Exception handling in Java allows programs to deal with errors and unexpected conditions gracefully. The try block encloses code that might throw exceptions. When an exception is thrown, the runtime system searches the call stack for a catch block that can handle the exception. The finally block always executes after the try and catch blocks complete to ensure cleanup code runs. Custom exceptions can be created by extending the Exception class.
Exception handling in C++ provides a standard mechanism for processing errors. Exceptions indicate problems during a program's execution and exception handling allows a program to continue running or notify the user of problems. The key components are try blocks for code that could cause exceptions, catch handlers to handle specific exceptions, and stack unwinding to search for exception handlers up the call stack if an exception is not caught. Derived exception classes enable related errors to be caught together under a base class.
This document provides an overview of exception handling in Java. It defines exceptions as events that disrupt normal program flow and discusses different types of exceptions including checked exceptions that must be handled and unchecked exceptions that do not require handling. It also covers how to declare, throw, and catch exceptions in code as well as best practices for logging exceptions. Finally, it summarizes exception handling in WebSphere Commerce, including application-specific and system exceptions.
This document discusses exception handling in .NET. It defines what exceptions are, how they are handled using try, catch, and finally blocks, and common exception types in .NET. The main points covered are:
- Exceptions are events that disrupt normal program flow due to errors.
- try and catch blocks allow handling exceptions, while finally ensures cleanup code runs.
- Common .NET exceptions inherit from System.Exception.
- Exceptions simplify error handling and make applications more robust.
The document discusses exception handling in Java. It defines exceptions as events that prevent an action from completing as intended. There are three types of exceptions: errors thrown by the JVM, runtime exceptions for logical errors, and checked exceptions for external issues. The try-catch block is used to handle exceptions, with catch blocks for specific exception types and finally for cleanup. Custom exceptions can be created by extending the Exception class.
Three key points about exception handling in C++ are:
1. Exceptions are used to handle runtime errors or exceptions and allow a program to continue running or exit gracefully rather than crashing.
2. Exception handling uses the try, throw, and catch keywords where code that can throw exceptions is wrapped in a try block, exceptions are thrown using throw, and catch blocks catch the exceptions.
3. When an exception is thrown in a try block, it bubbles up the call stack until a catch block that matches the exception type is found, allowing the exception to be handled.
Exceptions are a powerful mechanism for centralized processing of errors and exceptional situations. This mechanism replaces the procedure-oriented method of error handling in which each function returns a code indicating an error or a successful execution.
This document discusses exception handling in .NET. It defines what exceptions are, how they are handled using try, catch, and finally blocks, and common exception types in .NET like IndexOutOfRangeException and NullReferenceException. It explains that exceptions allow error handling code to be separated from the main program logic and that finally blocks ensure cleanup code is always executed.
The document discusses object oriented programming using C++. It covers the course objectives, which are to enable students to understand C++ constructs and relate them to engineering problems, and to improve their ability to analyze and address programming problems. It also lists the course outcomes and evaluation scheme. The content section defines exceptions, discusses exception handling using try, throw and catch, and covers the advantages and mechanism of exception handling. It provides examples of try-catch blocks and explains how to use exception handling in functions. Key applications of exception handling are also discussed.
This document discusses Java exception handling. It covers the exception hierarchy, keywords like try, catch, throw, throws and finally. It explains how to handle exceptions, create custom exception subclasses, and Java's built-in exceptions. Exception handling allows programs to define error handling blocks to gracefully handle runtime errors rather than crashing.
The exception hierarchy
Exception handling fundamentals
Try and catch
The consequences of an uncaught exception
Using multiple catch statements
Catching subclass exceptions
Nested try blocks
Throwing an exception
Re-throwing an exception
Using finally
Using throws
Java’s built-in exception
Creating exception subclasses
Exception handling allows programs to continue running or terminate gracefully when errors occur. There are several types of exceptions including errors, checked exceptions, and runtime exceptions. Code uses try-catch blocks to catch exceptions and handle them. Exceptions can be thrown from methods or from the JVM. Finally blocks are always executed to perform cleanup. Custom exception classes can be created by extending the Exception class.
This chapter discusses exception handling in C++. An exception is an undesirable event that occurs during program execution. A try/catch block is used to handle exceptions, where code that may cause exceptions is placed in the try block and catch blocks specify the exception type and handling code. When an exception is thrown in a try block, the corresponding catch block executes if the exception type matches. If no catch block matches, the call stack unwinds until the exception is caught or the program terminates.
The document discusses exception handling and multithreading in Java. It defines exceptions as unexpected events that occur during program execution and disrupt normal flow. There are three types of exceptions: checked exceptions which occur at compile time; unchecked exceptions which occur at runtime; and errors which are problems beyond a program's control. The try, catch, finally keywords are used to handle exceptions. The document also discusses creating threads and synchronization in multithreaded programming.
The document discusses exception handling and multithreading in Java. It begins by defining exceptions as unexpected events that occur during program execution and disrupt normal flow. There are three categories of exceptions: checked exceptions which occur at compile time; unchecked exceptions which occur at runtime; and errors which are problems beyond a program's control. The document then covers how to handle exceptions using try, catch, finally and throw keywords. It provides examples of built-in and user-defined exceptions. The document concludes by explaining Java's multithreading model, how to create and manage threads, set thread priorities and states, and techniques for inter-thread communication.
This document discusses exception handling in C++. It defines exceptions as problems that occur during program execution. Exception handling allows programs to continue running or gracefully exit after errors. The key aspects covered are:
- try/catch blocks define code that may throw exceptions and error handling code
- Functions can specify which exceptions they may throw
- Exceptions propagate up the call stack and are caught by outer blocks or cause program termination if uncaught
- Stack unwinding cleans up function calls as exceptions bubble up
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to continue running after exceptions rather than terminating. Key points:
- Exceptions are represented by objects in Java that describe errors.
- try-catch blocks allow handling exceptions within the catch block instead of terminating. finally blocks always execute regardless of exceptions.
- Checked exceptions must be caught or declared to be thrown; unchecked exceptions like NullPointerException represent programmer errors.
- Exceptions propagate up the call stack until caught unless declared as thrown. Exception handling prevents program termination due to errors.
Exception handling in Java allows programs to gracefully handle errors and unexpected conditions. The try block contains code that might throw exceptions, while catch blocks catch specific exception types. Finally blocks contain cleanup code that always executes whether an exception occurs or not. Programmers can throw exceptions themselves and catch or rethrow exceptions to defer handling to an outer scope. Finally blocks ensure resources are released properly.
Exceptions indicate problems during program execution and can be handled to allow programs to continue running or notify users. There are different levels where exceptions can occur including hardware, operating systems, languages, and within programs. Exception handling uses try, catch, and throw blocks. A try block encloses code that could throw an exception. If an exception occurs, control transfers to the matching catch block. The catch block handles the exception to resolve it. Exceptions not caught will terminate the program.
The document discusses error and exception handling in UiPath Studio. It defines different types of errors like syntax errors and exceptions. Exceptions are events caught and handled by the program. Common exceptions that may occur in UiPath projects are discussed, including NullReferenceException, IndexOutOfRangeException, and SelectorNotFoundException. The document also covers different exception handling techniques in UiPath like TryCatch, Throw, Rethrow, and the ContinueOnError property. Finally, it discusses the Global Exception Handler used to handle unexpected exceptions.
The document discusses exception handling in C#. It describes how exceptions are represented by classes derived from the System.Exception class. It explains the try, catch, throw, and finally keywords used to handle exceptions. Specific exception classes like DivideByZeroException are mentioned. Examples are provided to demonstrate catching individual exceptions, catching all exceptions, and throwing exceptions manually. Finally, it discusses using finally blocks and exploring exception object properties like Message and StackTrace.
Exception handling in Java allows programs to gracefully handle errors and unexpected conditions. There are two main types of exceptions - checked exceptions that must be declared and handled, and unchecked exceptions that do not require declaration. The try-catch block is used to catch and handle exceptions, while the finally block always executes to clean up resources regardless of whether an exception occurred or not. Custom exceptions can also be created to generate application-specific error messages.
The document outlines an end semester presentation by Group C on the topic of algorithms and computing labs. It includes the contents of the presentation which cover errors and exception handling basics, examples of exception occurrence and handling methods, and three example programs of increasing difficulty. It lists the group members and how presentation tasks were divided among them. It also includes details on grading criteria and a question/answer session.
The document discusses exception handling in Java. It defines exceptions as problems that disrupt normal program flow and defines exception handling as a mechanism to handle runtime errors. It describes different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains the exception hierarchy and how to use try, catch, and finally blocks to handle exceptions. Finally, it discusses user-defined exceptions, the throw keyword to explicitly throw exceptions, and the throws keyword to declare exceptions.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, 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: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
The document discusses exception handling in Java. It defines exceptions as events that prevent an action from completing as intended. There are three types of exceptions: errors thrown by the JVM, runtime exceptions for logical errors, and checked exceptions for external issues. The try-catch block is used to handle exceptions, with catch blocks for specific exception types and finally for cleanup. Custom exceptions can be created by extending the Exception class.
Three key points about exception handling in C++ are:
1. Exceptions are used to handle runtime errors or exceptions and allow a program to continue running or exit gracefully rather than crashing.
2. Exception handling uses the try, throw, and catch keywords where code that can throw exceptions is wrapped in a try block, exceptions are thrown using throw, and catch blocks catch the exceptions.
3. When an exception is thrown in a try block, it bubbles up the call stack until a catch block that matches the exception type is found, allowing the exception to be handled.
Exceptions are a powerful mechanism for centralized processing of errors and exceptional situations. This mechanism replaces the procedure-oriented method of error handling in which each function returns a code indicating an error or a successful execution.
This document discusses exception handling in .NET. It defines what exceptions are, how they are handled using try, catch, and finally blocks, and common exception types in .NET like IndexOutOfRangeException and NullReferenceException. It explains that exceptions allow error handling code to be separated from the main program logic and that finally blocks ensure cleanup code is always executed.
The document discusses object oriented programming using C++. It covers the course objectives, which are to enable students to understand C++ constructs and relate them to engineering problems, and to improve their ability to analyze and address programming problems. It also lists the course outcomes and evaluation scheme. The content section defines exceptions, discusses exception handling using try, throw and catch, and covers the advantages and mechanism of exception handling. It provides examples of try-catch blocks and explains how to use exception handling in functions. Key applications of exception handling are also discussed.
This document discusses Java exception handling. It covers the exception hierarchy, keywords like try, catch, throw, throws and finally. It explains how to handle exceptions, create custom exception subclasses, and Java's built-in exceptions. Exception handling allows programs to define error handling blocks to gracefully handle runtime errors rather than crashing.
The exception hierarchy
Exception handling fundamentals
Try and catch
The consequences of an uncaught exception
Using multiple catch statements
Catching subclass exceptions
Nested try blocks
Throwing an exception
Re-throwing an exception
Using finally
Using throws
Java’s built-in exception
Creating exception subclasses
Exception handling allows programs to continue running or terminate gracefully when errors occur. There are several types of exceptions including errors, checked exceptions, and runtime exceptions. Code uses try-catch blocks to catch exceptions and handle them. Exceptions can be thrown from methods or from the JVM. Finally blocks are always executed to perform cleanup. Custom exception classes can be created by extending the Exception class.
This chapter discusses exception handling in C++. An exception is an undesirable event that occurs during program execution. A try/catch block is used to handle exceptions, where code that may cause exceptions is placed in the try block and catch blocks specify the exception type and handling code. When an exception is thrown in a try block, the corresponding catch block executes if the exception type matches. If no catch block matches, the call stack unwinds until the exception is caught or the program terminates.
The document discusses exception handling and multithreading in Java. It defines exceptions as unexpected events that occur during program execution and disrupt normal flow. There are three types of exceptions: checked exceptions which occur at compile time; unchecked exceptions which occur at runtime; and errors which are problems beyond a program's control. The try, catch, finally keywords are used to handle exceptions. The document also discusses creating threads and synchronization in multithreaded programming.
The document discusses exception handling and multithreading in Java. It begins by defining exceptions as unexpected events that occur during program execution and disrupt normal flow. There are three categories of exceptions: checked exceptions which occur at compile time; unchecked exceptions which occur at runtime; and errors which are problems beyond a program's control. The document then covers how to handle exceptions using try, catch, finally and throw keywords. It provides examples of built-in and user-defined exceptions. The document concludes by explaining Java's multithreading model, how to create and manage threads, set thread priorities and states, and techniques for inter-thread communication.
This document discusses exception handling in C++. It defines exceptions as problems that occur during program execution. Exception handling allows programs to continue running or gracefully exit after errors. The key aspects covered are:
- try/catch blocks define code that may throw exceptions and error handling code
- Functions can specify which exceptions they may throw
- Exceptions propagate up the call stack and are caught by outer blocks or cause program termination if uncaught
- Stack unwinding cleans up function calls as exceptions bubble up
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to continue running after exceptions rather than terminating. Key points:
- Exceptions are represented by objects in Java that describe errors.
- try-catch blocks allow handling exceptions within the catch block instead of terminating. finally blocks always execute regardless of exceptions.
- Checked exceptions must be caught or declared to be thrown; unchecked exceptions like NullPointerException represent programmer errors.
- Exceptions propagate up the call stack until caught unless declared as thrown. Exception handling prevents program termination due to errors.
Exception handling in Java allows programs to gracefully handle errors and unexpected conditions. The try block contains code that might throw exceptions, while catch blocks catch specific exception types. Finally blocks contain cleanup code that always executes whether an exception occurs or not. Programmers can throw exceptions themselves and catch or rethrow exceptions to defer handling to an outer scope. Finally blocks ensure resources are released properly.
Exceptions indicate problems during program execution and can be handled to allow programs to continue running or notify users. There are different levels where exceptions can occur including hardware, operating systems, languages, and within programs. Exception handling uses try, catch, and throw blocks. A try block encloses code that could throw an exception. If an exception occurs, control transfers to the matching catch block. The catch block handles the exception to resolve it. Exceptions not caught will terminate the program.
The document discusses error and exception handling in UiPath Studio. It defines different types of errors like syntax errors and exceptions. Exceptions are events caught and handled by the program. Common exceptions that may occur in UiPath projects are discussed, including NullReferenceException, IndexOutOfRangeException, and SelectorNotFoundException. The document also covers different exception handling techniques in UiPath like TryCatch, Throw, Rethrow, and the ContinueOnError property. Finally, it discusses the Global Exception Handler used to handle unexpected exceptions.
The document discusses exception handling in C#. It describes how exceptions are represented by classes derived from the System.Exception class. It explains the try, catch, throw, and finally keywords used to handle exceptions. Specific exception classes like DivideByZeroException are mentioned. Examples are provided to demonstrate catching individual exceptions, catching all exceptions, and throwing exceptions manually. Finally, it discusses using finally blocks and exploring exception object properties like Message and StackTrace.
Exception handling in Java allows programs to gracefully handle errors and unexpected conditions. There are two main types of exceptions - checked exceptions that must be declared and handled, and unchecked exceptions that do not require declaration. The try-catch block is used to catch and handle exceptions, while the finally block always executes to clean up resources regardless of whether an exception occurred or not. Custom exceptions can also be created to generate application-specific error messages.
The document outlines an end semester presentation by Group C on the topic of algorithms and computing labs. It includes the contents of the presentation which cover errors and exception handling basics, examples of exception occurrence and handling methods, and three example programs of increasing difficulty. It lists the group members and how presentation tasks were divided among them. It also includes details on grading criteria and a question/answer session.
The document discusses exception handling in Java. It defines exceptions as problems that disrupt normal program flow and defines exception handling as a mechanism to handle runtime errors. It describes different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains the exception hierarchy and how to use try, catch, and finally blocks to handle exceptions. Finally, it discusses user-defined exceptions, the throw keyword to explicitly throw exceptions, and the throws keyword to declare exceptions.
Similar to lecture-c-corr-effkkkkkkkkkkkkkp (1).ppt (20)
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, 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: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
Communicating effectively and consistently with students can help them feel at ease during their learning experience and provide the instructor with a communication trail to track the course's progress. This workshop will take you through constructing an engaging course container to facilitate effective communication.
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxEduSkills OECD
Iván Bornacelly, Policy Analyst at the OECD Centre for Skills, OECD, presents at the webinar 'Tackling job market gaps with a skills-first approach' on 12 June 2024
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
2. Chapter 2: Program Correctness and Efficiency 2
Outline
• Categories of program errors
• Why you should catch exceptions
• The Exception hierarchy
• Checked and unchecked exceptions
• The try-catch-finally sequence
• Throwing an exception:
• What it means
• How to do it
3. Chapter 2: Program Correctness and Efficiency 3
Outline (continued)
• A variety of testing strategies
• How to write testing methods
• Debugging techniques and debugger
programs
• Program verification: assertions and loop
invariants
• Big-O notation
• What it is
• How to use it to analyze an algorithm’s efficiency
4. Chapter 2: Program Correctness and Efficiency 4
Program Defects and “Bugs”
• An efficient program is worthless if it breaks or
produces a wrong answer
• Defects often appear in software after it is
delivered
• Testing cannot prove the absence of defects
• It can be difficult to test a software product
completely in the environment in which it is used
• Debugging: removing defects
5. Chapter 2: Program Correctness and Efficiency 5
Major Categories of Defects
• Syntax and other in-advance errors
• Run-time errors and exceptions
• Logic Errors
6. Chapter 2: Program Correctness and Efficiency 6
Syntax Errors
• Syntax errors: grammatical mistakes in a program
• The compiler detects syntax errors
• You must correct them to compile successfully
• Some common syntax errors include:
• Omitting or misplacing braces, parentheses, etc.
• Misplaced end-of-comment
• Typographical errors (in names, etc.)
• Misplaced keywords
7. Chapter 2: Program Correctness and Efficiency 7
Semantic Errors
• Semantic errors: may obey grammar, but violate
other rules of the language
• The compiler detects semantic errors
• You must correct them to compile successfully
• Some common semantic errors include:
• Performing an incorrect operation on a primitive type value
• Invoking an instance method not defined
• Not declaring a variable before using it
• Providing multiple declarations of a variable
• Failure to provide an exception handler
• Failure to import a library routine
8. Chapter 2: Program Correctness and Efficiency 8
Run-time Errors or Exceptions
• Run-time errors
• Occur during program execution (run-time!)
• Occur when the JVM detects an operation that it
knows to be incorrect
• Cause the JVM to throw an exception
• Examples of run-time errors include
• Division by zero
• Array index out of bounds
• Number format error
• Null pointer exceptions
9. Chapter 2: Program Correctness and Efficiency 9
Run-time Errors or Exceptions (continued)
10. Chapter 2: Program Correctness and Efficiency 10
Logic Errors
• A logic error is programmer mistake in
• the design of a class or method, or
• the implementation of an algorithm
• Most logic errors
• Are not syntax or semantic errors: get by the compiler
• Do not cause run-time errors
• Thus they are difficult to find
• Sometimes found through testing
• Sometimes found by users
11. Chapter 2: Program Correctness and Efficiency 11
Avoiding Logic Errors
• Work from a precise specification
• Strive for clarity and simplicity
• Consider “corner” / extreme cases
• Have reviews / walk-throughs: other eyes
• Use library/published algorithms where possible
• Think through pre/post conditions, invariants
• Be organized and careful in general
12. Chapter 2: Program Correctness and Efficiency 12
The Exception Class Hierarchy
• When an exception occurs, the first thing that
happens is a new of a Java exception object
• Different exception classes have different rules
• Throwable is the root superclass of the exception
class hierarchy
• Error is a subclass of Throwable
• Exception is a subclass of Throwable
•RuntimeException is a subclass of Exception
13. Chapter 2: Program Correctness and Efficiency 13
The Class Throwable
• Throwable is the superclass of all exceptions
• All exception classes inherit its methods
14. Chapter 2: Program Correctness and Efficiency 14
The Class Throwable (continued)
15. Chapter 2: Program Correctness and Efficiency 15
The Exception Class Hierarchy (2)
Throwable is the superclass of all exception classes
• Error is for things a program should not catch
• Example: OutOfMemoryError
• Exception is for things a program might catch
• RuntimeException is for things the VM might throw
• It can happen anywhere: e.g., any object access can
throw NullPointerException
• So not required to catch it
• All others must be either:
• Explicitly caught or
• Explicitly mentioned as thrown by the method
16. Chapter 2: Program Correctness and Efficiency 16
Exception Hierarchy Summary
• Error: don’t catch, unchecked
• Exception:
• RuntimeException:
• (Usually) don’t catch, unchecked
• All others: checked, so must
• Catch, or
• Mention they may be thrown
17. Chapter 2: Program Correctness and Efficiency 17
Checked and Unchecked Exceptions
• Checked exceptions
• Normally not due to programmer error
• Generally beyond the control of the programmer
• Examples: IOException, FileNotFoundException
• Unchecked exception may result from
• Programmer error
• Serious external condition that is unrecoverable
18. Chapter 2: Program Correctness and Efficiency 18
Checked and Unchecked Exceptions (2)
unchecked
unchecked
19. Chapter 2: Program Correctness and Efficiency 19
Some Common Unchecked Exceptions
• ArithmeticException
• Division by zero, etc.
• ArrayIndexOutOfBoundsException
• NumberFormatException
• Converting a “bad” string to a number
• NullPointerException
• NoSuchElementException
• No more tokens available
20. Chapter 2: Program Correctness and Efficiency 20
Catching and Handling Exceptions
• When an exception is thrown, the normal
sequence of execution is interrupted
• Default behavior,i.e., no handler
• Program stops
• JVM displays an error message
• The programmer may provide a handler
• Enclose statements in a try block
• Process the exception in a catch block
21. Chapter 2: Program Correctness and Efficiency 21
Example Handler
InputStream in = null;
try {
in = new FileInputStream(args[0]);
...
} catch (FileNotFoundException e) {
System.out.printf(
“File not found: %s%n”, name);
} catch (Throwable e) {
System.err.println("Exception!");
e.printStackTrace(System.err);
} finally {
if (in != null) in.close();
}
22. Chapter 2: Program Correctness and Efficiency 22
Uncaught Exceptions
• Uncaught exception exits VM with a stack trace
• The stack trace shows
• The sequence of method calls
• Starts with throwing method
• Ends at main
23. Chapter 2: Program Correctness and Efficiency 23
The try-catch Sequence
• Avoiding uncaught exceptions
• Write a try-catch to handle the exception
• Point: prevent ugly program termination!
• Unpleasant for user
• Worse, may leave things messed up / “broken”
• catch block is skipped if no exception thrown
within the try block
24. Chapter 2: Program Correctness and Efficiency 24
Handling Exceptions to Recover from Errors
• Exceptions provide the opportunity to
• Report errors
• Recover from errors
• User errors common, and should be recoverable
• Most closely enclosing handler that matches is
the one that executes
• A handler matches if its class includes what’s thrown
• Compiler displays an error message if it
encounters an unreachable catch clause
25. Chapter 2: Program Correctness and Efficiency 25
The finally block
• On exception, a try is abandoned
• Sometimes more actions must be taken
• Example: Close an output file
• Code in a finally block is always executed
• After the try finishes normally, or
• After a catch clause completes
• finally is optional
26. Chapter 2: Program Correctness and Efficiency 26
Example of finally block
try {
InputStream ins = ...;
... ins.read(); ...
} catch (EOFException e) {
System.err.println(“Unexpected EOF”);
e.printStackTrace();
System.exit(17);
} finally {
if (ins != null) ins.close();
}
27. Chapter 2: Program Correctness and Efficiency 27
Throwing Exceptions
• Lower-level method can pass exception through
• Can be caught and handled by a higher-level method
• Mark lower-level method
• Say it may throw a checked exception
• Mark by throws clause in the header
• May throw the exception in the lower-level method
• Use a throw statement
• Particularly useful if calling module already has
a handler for this exception type
28. Chapter 2: Program Correctness and Efficiency 28
Throwing Exceptions (2)
• Use a throw statement when you detect an error
• Further execution stops immediately:
• Goes to closest suitable handler
• May be a number of level of calls earlier
• Does execute any finally blocks in the middle
29. Chapter 2: Program Correctness and Efficiency 29
Example of Throwing an Exception
/** adds a new entry or changes an old one
* @param name the name to create/update
* @param number the (new) number
* @return the previous number, a String
* @throws IllegalArgumentException if the number
* is not in phone number format
*/
public String addOrChangeEntry(
String name, String number) {
if (!isPhoneNumberFormat(number)) {
throw new IllegalArgumentException(
“Invalid phone number: “ + number);
}
...
}
30. Chapter 2: Program Correctness and Efficiency 30
Another Example of Throwing an Exception
public void accessLocalFile (String askingUser)
throws CertificateException {
...
if (user’s secure socket certificate bad) {
throw new CertificateException(reason);
}
...
}
31. Chapter 2: Program Correctness and Efficiency 31
Programming Style
• You can always avoid handling exceptions:
• Declare that they are thrown, or
• Throw them and let them be handled farther back
• But: usually best to handle instead of passing
• Guidelines:
1. If recoverable here, handle here
2. If checked exception likely to be caught higher up
Declare that it can occur using a throws clause
3. Don’t use throws with unchecked exceptions
Use an @throws javadoc comment when helpful
32. Chapter 2: Program Correctness and Efficiency 32
Programming Style (2)
Don’t do this!
try {...} catch (Throwable e) { }
• Omits arbitrary patches of code
Can leave things in “broken” state
• No warning to user
• Leads to hidden, difficult to detect, defects
33. Chapter 2: Program Correctness and Efficiency 33
Handling Exceptions in Phone Dir Example
In loadData:
FileNotFoundException from FileReader
constructor
IOException from readLine
In PDConsoleUI:
InputMismatchException from nextInt
In addOrChangeEntry:
IllegalArgumentException for empty String
34. Chapter 2: Program Correctness and Efficiency 34
Testing Programs
• A program with
• No syntax/semantic errors, and
• No run-time errors,
• May still contain logic errors
• “Best” case is logic error that always executes
• Otherwise, hard to find!
• Worst case is logic error in code rarely run
Goal of testing: Test every part of the code, on
“good” and “bad”/”hard” cases
35. Chapter 2: Program Correctness and Efficiency 35
Structured Walkthroughs
• Most logic errors:
• Come from the design phase
• Result from an incorrect algorithm
• Logic errors sometimes come from typos that do
not cause syntax, semantic, or run-time errors
• Famous FORTRAN: DO 10 I = 1.100
• Common C: if (i = 3) ...
• One way to test: hand-trace algorithm
before implementing!
• Thus: Structured Walkthroughs
36. Chapter 2: Program Correctness and Efficiency 36
Structured Walkthroughs (2)
The Designer:
• Explains the algorithm to other team members
• Simulate its execution with them looking on
The Team:
• Verifies that it works
• Verifies that it handles all cases
Walkthroughs are helpful, but do not replace testing!
37. Chapter 2: Program Correctness and Efficiency 37
Testing Defined
• Testing:
• Exercising a program under controlled conditions
• Verifying the results
• Purpose: detect program defects after
• All syntax/semantic errors removed
• Program compiles
• No amount of testing can guarantee the absence of
defects in sufficiently complex programs
38. Chapter 2: Program Correctness and Efficiency 38
Levels of Testing
• Unit testing: checking the smallest testable piece
• A method or class
• Integration testing:
• The interactions among units
• System testing: testing the program in context
• Acceptance testing: system testing intended to
show that the program meets its functional
requirements
39. Chapter 2: Program Correctness and Efficiency 39
Some Types of Testing
• Black-box testing:
• Tests item based only on its interfaces and
functional requirements
• Assumes no knowledge of internals
• White-box testing:
• Tests with knowledge of internal structure
40. Chapter 2: Program Correctness and Efficiency 40
Preparing to Test
• Develop test plan early, in the design phase
• How to test the software
• When to do the tests
• Who will do the testing
• What test data to use
• Early test plan allows testing during design & coding
• Good programmer practices defensive programming
• Includes code to detect unexpected or invalid data
41. Chapter 2: Program Correctness and Efficiency 41
Testing Tips for Program Systems
• Program systems contain collections of classes,
each with several methods
• A method specification should document
• Input parameters
• Expected results
• Carefully document (with javadoc, etc.):
• Each method parameter
• Each class attribute (instance and static variable)
• As you write the code!
42. Chapter 2: Program Correctness and Efficiency 42
Testing Tips for Program Systems (2)
Trace execution by displaying method name as
you enter a method:
public static final boolean TRACING = true;
...
public int computeWeight (...) {
if (TRACING) {
trace.printf(“Entering computeWeight“);
}
...
}
43. Chapter 2: Program Correctness and Efficiency 43
Testing Tips for Program Systems (3)
Display values of all input parameters on entry:
public int computeWeight (float volume,
float density) {
if (TRACING) {
trace.printf(“Entering computeWeight“);
trace.printf(“volume = %f, “, volume);
trace.printf(“density = %f%n“, density);
}
...
}
44. Chapter 2: Program Correctness and Efficiency 44
Testing Tips for Program Systems (4)
• Display values of any class attributes (instance
and static variables) accessed by the method
• Display values of all method outputs at point of
return from a method
• Plan for testing as you write each module,
• Not after the fact!
45. Chapter 2: Program Correctness and Efficiency 45
Developing Test Data
• Specify test data during analysis and design
• For each level of testing: unit, integration, and system
• Black-box testing: unit inputs outputs
• Check all expected inputs
• Check unanticipated data
• White-box testing: exercise all code paths
• Different tests to make each if test (etc.) true and false
• Called coverage
46. Chapter 2: Program Correctness and Efficiency 46
Developing Test Data (2)
• Helpful to do both black- and white-box testing
• Black-box tests can be developed early since
they have to do with the unit specification
• White-box tests are developed with detailed
design or implementation: need code structure
47. Chapter 2: Program Correctness and Efficiency 47
Testing Boundary Conditions
• Exercise all paths for
• Hand-tracing in a structured walkthrough
• Performing white-box testing
• Must check special cases:
boundary conditions
• Examples:
• Loop executes 0 times, 1 time, all the way to the end
• Item not found
48. Chapter 2: Program Correctness and Efficiency 48
Who does the testing?
• Normally testing is done by
• The programmer
• Team members who did not code the module
• Final users of the product
• Programmers often blind to their own oversights
• Companies may have quality assurance groups
• Extreme programming: programmers paired
• One writes the code
• The other writes the tests
49. Chapter 2: Program Correctness and Efficiency 49
Stubs for Testing
• Hard to test a method or class that interacts with
other methods or classes
• A stub stands in for a method not yet available
• The stub:
• Has the same header as the method it replaces
• Body only displays a message that it was called
• Sometimes you need to synthesize a reasonable
facsimile of a result, for the caller to continue
50. Chapter 2: Program Correctness and Efficiency 50
Drivers
A driver program:
• Declares necessary instances and variables
• Provides values for method inputs
• Calls the method
• Displays values of method outputs
• A main method in a class can serve as a driver
to test the class’s methods
51. Chapter 2: Program Correctness and Efficiency 51
Regression Testing
• Once code has passed all initial tests, it is
important to continue to test regularly
• Environment and other changes “software rot”
• A regression test is designed to:
• Catch any “regression” or decay in the software
• Insure old functionality works in face of enhancement
• Alert earlier to any issues arising from other changes
• Regression testing eased by a testing framework
52. Chapter 2: Program Correctness and Efficiency 52
Using a Testing Framework
Testing framework: software that facilitates:
• Writing test cases
• Organizing the test cases into test suites
• Running the test suites
• Reporting the results
53. Chapter 2: Program Correctness and Efficiency 53
JUnit
• A Java testing framework
• Open-source product
• Can be used stand-alone or with an IDE
• Available from junit.org
54. Chapter 2: Program Correctness and Efficiency 54
JUnit Example
import junit.framework.*;
public class TestDirectoryEntry
extends TestCase {
private DirectoryEntry tom;
private DirectoryEntry dick;
private DirectoryEntry tom2;
public void setUp () {
tom = new DirectoryEntry(“Tom” , “...”);
dick = new DirectoryEntry(“Dick”, “...”);
tom2 = new DirectoryEntry(“Tom” , “...”);
}
55. Chapter 2: Program Correctness and Efficiency 55
JUnit Example (2)
public void testTomCreate () {
assertEquals(tom.getName() , “Tom”);
assertEquals(tom.getNumber(), “...”);
}
public void testTomEqualsDick () {
assertFalse(tom.equals(dick));
assertFalse(dick.equals(tom));
}
56. Chapter 2: Program Correctness and Efficiency 56
JUnit Example (3)
public void testTomEqualsTom () {
assertTrue(tom.equals(tom));
assertTrue(tom.equals(tom2));
assertTrue(tom2.equals(tom));
}
public void testSetNumber () {
dick.setNumber(tom.getNumber());
assertEquals(tom.getNumber(),dick.getNumber());
}
57. Chapter 2: Program Correctness and Efficiency 57
Integration Testing
• Larger components: collection of classes
• Done with smaller collection, then larger ones
• Drive with use cases: scenarios with
• Sample user inputs
• Expected outputs
• Can be challenging to automate
58. Chapter 2: Program Correctness and Efficiency 58
Debugging a Program
Debugging: the major activity during the testing phase
• Testing determines that there is an error
• Debugging determines the cause
• Debugging is like detective work: logical deduction
• Inspect all program output carefully
• Insert additional output statements to find out more
• Use breakpoints to examine world ...
at carefully selected points
59. Chapter 2: Program Correctness and Efficiency 59
Using a Debugger
• Debuggers often are included with IDEs
• Debugger supports incremental program execution
• Single-step execution provides increments as small as
one program statement (or even one instruction)
• Breakpoints traverse larger portions of code at once
• Details depend on the specfic IDE
Key to debugging: Think first! Think a lot!
• Also: try to split possible error sources in half with
each investigation
60. Chapter 2: Program Correctness and Efficiency 60
Reasoning about Programs:
Assertions and Loop Invariants
• Assertions:
• Logical statements about program state
• Claimed to be true
• At a particular point in the program
• Written as a comment, OR use assert statement
• Preconditions and postconditions are assertions
• Loop invariants are also assertions
61. Chapter 2: Program Correctness and Efficiency 61
Reasoning about Programs:
Loop Invariants
A loop invariant:
• Helps prove that a loop meets it specification
• Is true before loop begins
• Is true at the beginning of each iteration
• Is true just after loop exit
Example: Sorting an array of n elements
Sorted(i): Array elements j, for 0 ≤ j < i, are sorted
Beginning: Sorted(0) is (trivially) true
Middle: We insure initial portion sorted as we increase i
End: Sorted(n): All elements 0 ≤ j < n are sorted
62. Chapter 2: Program Correctness and Efficiency 62
Efficiency of Algorithms
Question: How can we characterize the
performance of an algorithm ...
• Without regard to a specific computer?
• Without regard to a specific language?
• Over a wide range of inputs?
Desire: Function that describes execution time in
terms of input size
• Other measures might be memory needed, etc.
63. Chapter 2: Program Correctness and Efficiency 63
The “Order” of Performance: (Big) O
• Basic idea:
1. Ignore constant factor: computer and language
implementation details affect that: go for
fundamental rate of increase with problem size.
2. Consider fastest growing term: Eventually, for large
problems, it will dominate.
• Value: Compares fundamental performance
difference of algorithms
• Caveat: For smaller problems, big-O worse
performer may actually do better
64. Chapter 2: Program Correctness and Efficiency 64
T(n) = O(f(n))
• T(n) = time for algorithm on input size n
• f(n) = a simpler function that grows at about the
same rate
• Example: T(n) = 3n2+5n-17 = O(n2)
• f(n) has faster growing term
• no extra leading constant in f(n)
65. Chapter 2: Program Correctness and Efficiency 65
T(n) = O(f(n)) Defined
1. n0 and
2. c such that
If n > n0 then c·f(n) ≥ T(n)
Example: T(n) = 3n2+5n-17
Pick c = 4, say; need 4n0
2 > 3n0
2+5n0-17
n0
2 > 5n0-17, for which n0 = 5 will do.
66. Chapter 2: Program Correctness and Efficiency 66
Efficiency of Algorithms (continued)
67. Chapter 2: Program Correctness and Efficiency 67
Efficiency of Algorithms (continued)
68. Chapter 2: Program Correctness and Efficiency 68
Efficiency of Algorithms (continued)
69. Chapter 2: Program Correctness and Efficiency 69
Efficiency of Algorithms (continued)
70. Chapter 2: Program Correctness and Efficiency 70
Efficiency of Algorithms (continued)
71. Chapter 2: Program Correctness and Efficiency 71
Efficiency Examples
public static int find (int[]x, int val) {
for (int i = 0; i < x.length; i++) {
if (x[i] == val)
return i;
}
return -1; // not found
}
Letting n be x.length:
Average iterations if found = (1+...+n)/n = (n+1)/2 = O(n)
Iterations if not found = n = O(n)
Hence this is called linear search.
72. Chapter 2: Program Correctness and Efficiency 72
Efficiency Examples (2)
public static boolean allDifferent (
int[] x, int[] y) {
for (int i = 0; i < x.length; i++) {
if (find(y, x[i]) != -1)
return false;
}
return true; // no x element found in y
}
Letting m be x.length and n be y.length:
Time if all different = O(m·n) = m · cost of search(n)
73. Chapter 2: Program Correctness and Efficiency 73
Efficiency Examples (3)
public static boolean unique (int[] x) {
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x.length; j++ {
if (i != j && x[i] == x[j])
return false;
}
}
return true; // no duplicates in x
}
Letting n be x.length:
Time if unique = n2 iterations = O(n2)
74. Chapter 2: Program Correctness and Efficiency 74
Efficiency Examples (4)
public static boolean unique (int[] x) {
for (int i = 0; i < x.length; i++) {
for (int j = i+1; j < x.length; j++ {
if (i != j && x[i] == x[j])
return false;
}
}
return true; // no duplicates in x
}
Letting n be x.length:
Time if unique = (n-1)+(n-2)+...+2+1 iterations =
n(n-1)/2 iterations = O(n2) still ... only factor of 2 better
75. Chapter 2: Program Correctness and Efficiency 75
Efficiency Examples (5)
for (int i = 1; i < n; i *= 2) {
do something with x[i]
}
Sequence is 1, 2, 4, 8, ..., ~n.
Number of iterations = log2n = log n.
Computer scientists generally use base 2 for log, since
that matches with number of bits, etc.
Also O(logbn) = O(log2n) since chane of base just
multiples by a constant: log2n = logbn/logb2
76. Chapter 2: Program Correctness and Efficiency 76
Chessboard Puzzle
Payment scheme #1: $1 on first square, $2 on second,
$3 on third, ..., $64 on 64th.
Payment scheme #2: 1¢ on first square, 2¢ on second,
4¢ on third, 8¢ on fourth, etc.
Which is best?
77. Chapter 2: Program Correctness and Efficiency 77
Chessboard Puzzle Analyzed
Payment scheme #1: Total = $1+$2+$3+...+$64 =
$6465/2 = $1755
Payment scheme #2: 1¢+2¢+4¢+...+263¢ = 264-1¢ =
$184.467440737 trillion
Many cryptographic schemes require O(2n) work to
break a key of length n bits. A key of length n=40 is
perhaps breakable, but one with n=100 is not.