This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
In this page, we will learn about the basics of OOPs. Object-Oriented Program...Indu32
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.
Java developer trainee implementation and importiamluqman0403
The document discusses different types of software including standalone apps, client/server apps, and web applications; it also defines key terms like program, software, and describes the different layers of web applications including the presentation, application, and data layers.
Fundamentals of Programming Lecture #1.pptxEyasu46
This document provides an overview of programming and problem solving concepts. It discusses that a problem is a situation that needs resolution, while a solution removes the problematic situation. Problem solving is the process of deriving a solution. Programming involves creating computer solutions to problems through algorithms expressed as programs. Key steps for problem solving are understanding the problem, planning an algorithm/solution, implementing it as a program, testing the program, documenting it, and maintaining it for changes. Pseudocode and flowcharts are common ways to describe algorithms before implementing them as programs.
Euclid's algorithm is a method for finding the greatest common divisor (GCD) of two numbers. It works by taking the remainder of dividing the larger number by the smaller number at each step, and repeating this process until the remainder is zero. The last non-zero remainder is the GCD. The key steps are: (1) Take the remainder of dividing the two input numbers; (2) Set the smaller number equal to the remainder, and repeat from step 1 until the remainder is zero.
Here are the steps to solve the problems using IPO table, pseudo code and flowchart:
1. Define the problem and understand requirements
2. Make IPO table:
- Input, Process, Output
3. Write pseudo code using proper indentation and comments
4. Draw flowchart using standard symbols
5. Test and debug the program
This systematic approach helps analyze the problem, design the algorithm and implement it properly. The key is breaking down the problem into smaller understandable steps.
2-Algorithms and Complexit data structurey.pdfishan743441
The document discusses algorithms design and complexity analysis. It defines an algorithm as a well-defined sequence of steps to solve a problem and notes that algorithms always take inputs and produce outputs. It discusses different approaches to designing algorithms like greedy, divide and conquer, and dynamic programming. It also covers analyzing algorithm complexity using asymptotic analysis by counting the number of basic operations and deriving the time complexity function in terms of input size.
أساسيات البرمجة - شرح بإستخدام لغة السى بلس بلس - C++
https://www.youtube.com/watch?v=Fr6wJ5_Hok0&list=PL1DUmTEdeA6IUD9Gt5rZlQfbZyAWXd-oD
This document provides an overview of the Python programming language. It discusses what a program and programming language are, and then describes key features of Python like being simple, interactive, and object-oriented. It explains how to install Python and work in interactive and script modes. The document also covers Python concepts like variables, data types, functions, operators, and control structures like conditional statements and loops.
The document discusses algorithms, flowcharts, and pseudocode. It begins by defining algorithms as step-by-step processes to solve problems and notes that computer programs are algorithms written in a programming language. It then discusses flowcharts as visual representations of algorithms using standard symbols. The rest of the document provides details on flowchart symbols, rules for flowcharting, examples of flowcharts, and exercises to create flowcharts. It also defines pseudocode as a way to describe algorithms in plain English and provides examples of how to write pseudocode using basic programming constructs like sequence, selection, and repetition.
The document discusses algorithms and flowcharts. It defines an algorithm as a finite set of steps to solve a problem and notes that algorithms can be expressed in various ways, including pseudocode and flowcharts. Pseudocode uses a language similar to programming but without specific syntax, making it readable by programmers familiar with different languages. A flowchart provides a graphical representation of an algorithm's logical flow. The document provides examples of algorithms expressed in pseudocode and represented through flowcharts, such as finding the average of two numbers and calculating the largest of several inputs. It also discusses common flowchart structures like sequence, selection, and iteration.
02 functions, variables, basic input and output of c++Manzoor ALam
This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
01 Introduction to analysis of Algorithms.pptxssuser586772
An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks.
An algorithm is an efficient method that can be expressed within finite amount of Time and space.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. To Evaluate An Algorithm we have to Satisfy the following Criteria:
INPUT: The Algorithm should be given zero or more input.
OUTPUT: At least one quantity is produced. For each input the algorithm produced value from specific task.
DEFINITENESS: Each instruction is clear and unambiguous.
FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps.
EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using only pencil & paper.Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem.
Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language.
Program : It is exact code written for problem following all the rules of the programming language.Algorithm can be described (Represent) in four ways.
Natural language like English:
When this way is chooses, care should be taken, we
should ensure that each & every statement is definite.
(no ambiguity)
2. Graphic representation called flowchart:
This method will work well when the algorithm is small& simple.
3. Pseudo-code Method:
In this method, we should typically describe algorithms as
program, which resembles language like Pascal & Algol
(Algorithmic Language).
4.Programming Language:
we have to use programming language to write algorithms like
C, C++,JAVA etc.Comments begin with // and continue until the end of line.
Blocks are indicated with matching braces { and }.
An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
1.How to create an algorithm: To create an algorithm we have following design technique
a) Divide & Conquer
b) Greedy method
c) Dynamic Programming
d) Branch & Bound
e) Backtracking
2.How to validate an algorithm:
Once an algorithm is created it is necessary to show that it computes the correct Pr
This document provides an introduction to Java programming through a 3-part Java 101 tutorial. It covers setting up a development environment, an overview of the Java language, and how to write a simple "Hello World" program. It also introduces key Java concepts like data types, conditionals, loops, and classes. The document includes code examples and exercises for hands-on learning.
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
This document provides an introduction to Java programming through a series of Java 101 tutorials. It discusses setting up a Java development environment, provides an overview of the Java language, and demonstrates how to write a first Java program. It also covers built-in Java data types like String, int, double, and boolean, and control structures like conditionals and loops. The document concludes with exercises for readers to practice working with command line arguments, operators, arrays, and random number generation in Java.
The document discusses problem solving skills in computer programming. It explains the four basic operations of input, output, processing, and storage. It provides examples of how each operation is represented in pseudocode. The document also outlines the steps for problem solving, including defining the problem, creating an algorithm using pseudocode, and implementing the algorithm in a programming language. It provides examples of algorithms and flowcharts to illustrate problem solving techniques.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It also demonstrates how to compile and run a simple Java application and includes examples of code snippets.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
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.
أساسيات البرمجة - شرح بإستخدام لغة السى بلس بلس - C++
https://www.youtube.com/watch?v=Fr6wJ5_Hok0&list=PL1DUmTEdeA6IUD9Gt5rZlQfbZyAWXd-oD
This document provides an overview of the Python programming language. It discusses what a program and programming language are, and then describes key features of Python like being simple, interactive, and object-oriented. It explains how to install Python and work in interactive and script modes. The document also covers Python concepts like variables, data types, functions, operators, and control structures like conditional statements and loops.
The document discusses algorithms, flowcharts, and pseudocode. It begins by defining algorithms as step-by-step processes to solve problems and notes that computer programs are algorithms written in a programming language. It then discusses flowcharts as visual representations of algorithms using standard symbols. The rest of the document provides details on flowchart symbols, rules for flowcharting, examples of flowcharts, and exercises to create flowcharts. It also defines pseudocode as a way to describe algorithms in plain English and provides examples of how to write pseudocode using basic programming constructs like sequence, selection, and repetition.
The document discusses algorithms and flowcharts. It defines an algorithm as a finite set of steps to solve a problem and notes that algorithms can be expressed in various ways, including pseudocode and flowcharts. Pseudocode uses a language similar to programming but without specific syntax, making it readable by programmers familiar with different languages. A flowchart provides a graphical representation of an algorithm's logical flow. The document provides examples of algorithms expressed in pseudocode and represented through flowcharts, such as finding the average of two numbers and calculating the largest of several inputs. It also discusses common flowchart structures like sequence, selection, and iteration.
02 functions, variables, basic input and output of c++Manzoor ALam
This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
01 Introduction to analysis of Algorithms.pptxssuser586772
An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks.
An algorithm is an efficient method that can be expressed within finite amount of Time and space.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. To Evaluate An Algorithm we have to Satisfy the following Criteria:
INPUT: The Algorithm should be given zero or more input.
OUTPUT: At least one quantity is produced. For each input the algorithm produced value from specific task.
DEFINITENESS: Each instruction is clear and unambiguous.
FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps.
EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using only pencil & paper.Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem.
Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language.
Program : It is exact code written for problem following all the rules of the programming language.Algorithm can be described (Represent) in four ways.
Natural language like English:
When this way is chooses, care should be taken, we
should ensure that each & every statement is definite.
(no ambiguity)
2. Graphic representation called flowchart:
This method will work well when the algorithm is small& simple.
3. Pseudo-code Method:
In this method, we should typically describe algorithms as
program, which resembles language like Pascal & Algol
(Algorithmic Language).
4.Programming Language:
we have to use programming language to write algorithms like
C, C++,JAVA etc.Comments begin with // and continue until the end of line.
Blocks are indicated with matching braces { and }.
An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
1.How to create an algorithm: To create an algorithm we have following design technique
a) Divide & Conquer
b) Greedy method
c) Dynamic Programming
d) Branch & Bound
e) Backtracking
2.How to validate an algorithm:
Once an algorithm is created it is necessary to show that it computes the correct Pr
This document provides an introduction to Java programming through a 3-part Java 101 tutorial. It covers setting up a development environment, an overview of the Java language, and how to write a simple "Hello World" program. It also introduces key Java concepts like data types, conditionals, loops, and classes. The document includes code examples and exercises for hands-on learning.
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
This document provides an introduction to Java programming through a series of Java 101 tutorials. It discusses setting up a Java development environment, provides an overview of the Java language, and demonstrates how to write a first Java program. It also covers built-in Java data types like String, int, double, and boolean, and control structures like conditionals and loops. The document concludes with exercises for readers to practice working with command line arguments, operators, arrays, and random number generation in Java.
The document discusses problem solving skills in computer programming. It explains the four basic operations of input, output, processing, and storage. It provides examples of how each operation is represented in pseudocode. The document also outlines the steps for problem solving, including defining the problem, creating an algorithm using pseudocode, and implementing the algorithm in a programming language. It provides examples of algorithms and flowcharts to illustrate problem solving techniques.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It also demonstrates how to compile and run a simple Java application and includes examples of code snippets.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
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.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
its all about Artificial Intelligence(Ai) and Machine Learning and not on advanced level you can study before the exam or can check for some information on Ai for project
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
Data Structures_Linear data structures Linked Lists.pptxRushaliDeshmukh2
Concept of Linear Data Structures, Array as an ADT, Merging of two arrays, Storage
Representation, Linear list – singly linked list implementation, insertion, deletion and searching operations on linear list, circularly linked lists- Operations for Circularly linked lists, doubly linked
list implementation, insertion, deletion and searching operations, applications of linked lists.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
3. What Is Programming and Program Development Life Cycle ?
• Programming is a process of problem solving
• Step 1: Analyze the problem
– Understand the Overall problem
– Define problem requirements
• Does program require user interaction?
– If yes , What Is the Input ?
• What is the Expected output?
– Design steps (algorithm) to solve the problem
3
Output
Processing
Input
Algorithm:
Step-by-step problem-solving process
4. • Step 2: Implement the algorithm
– Implement the algorithm in code
– Verify that the algorithm works
• Step 3: Maintenance
– Use and modify the program if the problem domain changes
4
What Is Programming and Program Development Life Cycle ?
If the problem is complex, divide it into sub-problems
Analyze each sub-problem as above
5. Example
• Write a program to find the Area of a rectangle
The area of the Rectangle are given by the following formula:
Area = Rect Length * Rect Width.
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
5
13. Processing a Java Program
13
Source Code
Create/Modify Source Code
Compile Source Code
i.e., javac Welcome.java
Bytecode
Run Byteode
i.e., java Welcome
Result
If compilation errors
If runtime errors or incorrect result
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
stored on the disk
Source code (developed by the programmer)
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
14. 14
Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
15. • We can put comment on our programs using
• // to comment a single line
// this progrm is written by mohamed El desouki
• /*
Mulitple Lines
• */ to comment multiple lines
/* This program is written by Mohamed El Desouki
On Monday 11/1/2018
*/
15
Comments
17. Interacting With User: Displaying Messages on Screen
• In Java, we use System.out.print ( ) Or System.out.println () To be Display text on The screen
17
18. • He said that “Iam From Egypt” but lives in “KSA”
– System.out.print(“ He Said That “Iam From Egypt ” but lives in “KSA” “)
• The Files located in D:javaprorgtryoutput
– System.out.print(“The Files located in D:javaprorgtryoutput “)
• Sunday Monday Tuesday Wednesday Thursday
– System.out.print(“Sunday t Monday t Tuesday t Wednesdayt Thursday“)
18
Interacting With User: Displaying Messages on Screen
22. Java Data Types
22
char
Character or small
integer.
1byte
signed: -128 to 127
unsigned: 0 to 255
int Integer. 4bytes
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
short int
(short)
Short Integer. 2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
long int (long) Long integer. 4bytes
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
bool
Boolean value. It can
take one of two values:
true or false.
1byte true or false
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double
Double precision
floating point number.
8bytes +/- 1.7e +/- 308 (~15 digits)
long double
Long double precision
floating point number.
8bytes +/- 1.7e +/- 308 (~15 digits)
23. 23
Interacting With User: Accept Input From User
• A variable is a location in the computer’s memory where a value can be stored for use by a program.
• All variables must be declared with a name and a data type before they can be used in a program.
• Declaration : DataType Identifier
24. Example 1
• Write a program to find the Area of a rectangle
The area of the Rectangle are given by the following formula:
Area = Rect Length * Rect Width.
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
24
25. Working With Variable
25
Int length ;
Int width;
Int area;
Scanner input = new Scanner(System.in);
Length = input.nextInt();
Width = input.nextInt();
Area = Length * width ;
Length
Width
area
5
10
50
26. Example 2
• Write a program to find the perimeter and area of a square
The perimeter and area of the square are given by the following formulas:
perimeter = Side Length * 4
area = Side Length * Side Length
Input:
Square Side Length
Processing:
perimeter = Side Length * 4
area = Side Length * Side Length
Output:
Print Out The Perimeter and Area.
26
32. • ? = 1 + 2 * (3 + 4)
– Evaluated as 1 + (2 * (3+4)) and the result is 15
• ? = 5 * 2 + 9 % 4
– Evaluated as (5*2) + (9 % 4) and the result is 11
• ? = 5 * 2 % ( 7 – 4)
– Evaluated as (5 * 2) % (7 – 4) and the result is 1
32
Precedence of arithmetic operations
33. Data Type of an Arithmetic Expression
• Data type of an expression depends on the type of its operands
– Data type conversion is done by the compiler
• If operators are *, /, +, or – , then the type of the result will be:
– integer, if all operands are integer.
» Int A , B;
» A+ B Integer.
– float, If at least one operand is float and there is no double
» Int A ; Float B;
» A + B Float.
– double, if at least one operand is double
• Int A ; Float B; Double C;
» A + B + C double.
33
35. Increment and Decrement Operators
• If the value produced by ++ or – – is not used in an expression, it does not matter whether it is a
pre or a post increment (or decrement).
• When ++ (or – –) is used before the variable name, the computer first increments (or
decrements) the value of the variable and then uses its new value to evaluate the expression.
• When ++ (or – –) is used after the variable name, the computer uses the current value of the
variable to evaluate the expression, and then it increments (or decrements) the value of the
variable.
• There is a difference between the following
35
x = 5;
Print(++x);
x = 5;
Print (x++);
36. special assignment statements
36
• Java has special assignment statements called compound assignments
+= , -= , *= , /= , %=
• Example:
X +=5 ; means x = x + 5;
x *=10; means x = x * 10;
x /=5; means x = x / 5;
39. Control Statements
• Normally, statements in a program are executed one after the other in the order in which they’re written.
• This is called sequential execution.
• There are control statements enable you to specify that the next statement to be executed may be other than
the next one in sequence.
• This is called transfer of control.
• The control statements are categorized in almost two groups:
Selection control statements
Repetition control statements
41. • Selection statements are used to choose among alternative courses of action.
• For example, suppose the passing mark on an exam is 60. The pseudocode statement
– If student’s marks is greater than or equal to 60 Then
Print “Passed”
Selection Statements : If Statement
42. 42
if ( Expression)
action statement ;
if ( Expression)
{
action statement 1 ;
action statement 2 ;
.
.
action statement n ;
}
In Java, The syntax for the If statement
if ( grade >= 60 )
System.out.println (“Passed”);
• The Expression can be any valid expression
including a relational expression and even
arithmetic expression
• In case of using arithmetic expressions , a non-
zero value is considered to be true, whereas a 0 is
considered to be false
43. Relational Expression and Relational Operators
43
Operator Means
== Equal To
!= Not Equal To
< Less Than
<= Less Than or Equal To
> Greater Than
>= Greater Than or Equal To
• Relational expression is an expression which compares 2 operands and returns a TRUE or FALSE
answer.
Example : a >= b , a == c , a >= 99 , ‘A’ > ‘a’
• Relational expressions are used to test the conditions in selection, and looping statements.
44. Example : write a program that accept an integer from the user and in case this integer is even print out
the following message
“This number is even “ .
44
Selection Statements : If Statement
45. • The IF…Else selection statement allows you to specify that there is a course of actions are to be performed
when the condition is true and another course of actions will be executed when the condition is false.
• For example, the pseudocode statement
– If student’s mark is greater than or equal to 60
Print “Passed”
else
Print “Failed”
Selection Statements : If .. Else Statement
46. 46
if ( Expression)
action statement ;
Else
action statement ;
if ( Expression)
{
action statements 1 ;
.
action statement n ;
}
Else
{
action statements 1 ;
.
action statement n ;
}
In Java, The syntax for the If…Else statement
if ( grade >= 60 )
System.out.println("Passed“);
Else
47. Example : write a program that accept an integer from the user and
print out whether it is Positive or Negative number.
47
Selection Statements : If – else Statement
49. Nested If
49
• Nested If : means to write an if statement within another if statement.
Example : write a program that accept an integer number from the user ,
in case the number is Positive , check and print out whether it is Even or Odd number.
int main()
{
int number;
System.out.println("Please Enter any number “) ;
Number = input.nextInt();
if ( number >=0)
if (number % 2 == 0)
System.out.println(" This is an Even number
“);
else
System.out.println("This is an Odd number“);
}
50. IF – Else IF statement
50
• For example, write a program that ask the user to Enter 2 numbers and print out whether they are equal or there is one which is greater
than the other.
main()
{
int num1, num2;
System.out.println("Enter Number 1 , Number2 “);
Num1= input.nextInt();
Num2= input.nextInt();
if ( num1 == num2 )
System.out.println ("Both Are Equal “);
else if (num1 > num2 )
System.out.println("Number 1 is greater than number 2 “);
else
System.out.println ("Number 2 is greater than number 1 “);
}
51. IF – Else IF
51
• For example, the following code will print
A for exam grades greater than or equal to 90,
B for grades greater than or equal to 80,
C for grades greater than or equal to 70,
D for grades greater than or equal to 60, and
F for all other grades.
– if ( grade >= 90 )
System.out.println( "A“) ;
else if ( grade >= 80 )
System.out.println( "B”);
else if ( grade >= 70 )
System.out.println("C”);
else if ( grade >= 60 )
System.out.println("D”);
else
System.out.println("F“) ;
52. Combining more than one condition
52
Operator Means Description
&& And The Expression Value Is true If and Only IF both
Conditions are true
|| OR The Expression Value Is true If one Condition Is True
• To combine more than one condition we use the logical operators.
Example : check whether num1 is between 0 and 100
IF ( num1 >= 0 && num1 <=100 )
System.out.println (“The Number Is between 1 and 100”) ;
Else
System.out.println( “ The Number Is Larger Than 100”);
53. 53
Example, print out the student grade according to the following formulas:
A for exam marks greater than or equal 90 and less than or equal 100 ,
B for exam marks greater than or equal 80 and less than 90 ,
C for exam marks than or equal to 70 and less than 80 ,
D for exam marks than or equal to 60, and less than 70 ,
F for all other marks.
– if ( marks >= 90 && marks <= 100)
System.out.println ( "A“ );
else if (marks >= 80 && marks <90 )
System.out.println ( "B”);
else if (marks >= 70 && marks <80 )
System.out.println ( "C”);
else if (marks >= 60 && marks <70 )
System.out.println ( "D”);
else
System.out.println ( "Fn“) ;
Combining more than one condition
54. Example : A company insures its Employees in the following cases:
– Employee is married.
– Employee is an Single male above 30 years of age.
– Employee is an Single female above 25 years of age.
– Conditions :
1. Marital status = ‘M’; OR
2. Marital Status =‘S’ and Sex=‘M’ and Age >30 OR
3. Marital Status =‘S’ and Sex=‘F’ and Age >25
54
57. Selection statements: Switch Statement.
57
The switch control statement allows us to make a decision from the number of
choices
Switch (Expression )
{
case constant 1 :
Action statements;
break ;
case constant 2 :
Action statements;
break ;
case constant 3 :
Action statements;
break ;
default :
Action statements;
}
Expression It could be an integer
constant like 1, 2 or 3, or an
expression that evaluates to an
integer .
Constant : is a specific value.
Switch (10.0);
float i ;
Switch (i);
switch ( i + j * k )
switch ( 23 + 45 % 4 * k
)
Case >= 50;
Case a+ b;
Switch (10);
Int i ;
Switch (i);
switch ( 23 + 45 % 4 * k )
59. 59
1. The switch Statement
public static void main (String[] args)
{
//Declaration section
Scanner read = new Scanner (System.in);
char grade;
String message;
//input section
grade = read.next().charAt(0);
//processing section
switch (grade)
{
case ‘A’: message = “Excellent”;
break;
case ‘B’: message = “Very Good”;
break;
case ‘C’: message = “Good”;
break;
case ‘D’: message = “Fair”;
break;
case ‘F’: message = “Failed”;
break;
default: message =“The grade is invalid”;
} //end switch
//output section
System.out.println (message);
} //end main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if (grade == ‘A’)
message = “Excellent”;
Else if (grade == ‘B’)
message = “Very Good”;
else if (grade == ‘C’)
message = “Good”;
else if (grade == ‘D’)
message = “Fair”;
else if (grade == ‘F’)
message = “Fail”;
else message = “The grade is invalid”;
System.out.println (message);
60. Write a program that displays the following menu, then acts accordingly:
Enter your choice:
1. Add two numbers
2. Get the Subtract of two number
3. Get the square of a number
The program should give an error message for invalid inputs.
61. public static void main (String[] args)
{
Scanner read = new Scanner (System.in);
int choice, num1, num2, result = -1;
String message = “Invalid input”;
System.out.println (“Enter your choice:”);
System.out.println (“1. Add two numbers”);
System.out.println (“2. Get the double of a positive number”);
System.out.println (“3. Get the square of a number”);
choice = read.nextInt();
//processing section
switch (choice)
{
case 1: System.out.println (“Enter two positive integers”); //prompt
num1 = read.nextInt();
num2 = read.nextInt();
result = num1 + num2; // the value of result is no more equal to -1
break;
case 2: System.out.println (“Enter a positive integer”); //prompt
num1 = read.nextInt();
num2 = read.nextInt();
result = num1 – num2;
break;
case 3: System.out.println (“Enter an integer”); //prompt
num1 = read.nextInt();
result = num1 * num1; // the value of result is no more equal to -1
break;
default: message =“Invalid value of choice”; //no change to “result” result=-1
} //end switch
62. public static void main (String[] args)
{
//Declaration section
Scanner read = new Scanner (System.in);
char letter;
String vowel = “This is a vowel”;
//input section
letter = read.next().charAt(0);
//processing section
switch (letter)
{
case ‘a’:
case ‘e’:
case ‘o’:
case ‘i’:
case ‘u’: System.out.println (vowel);
break;
default: System.out.println (“This is not a vowel”);
} //end switch
} //end main
6
2
When the same action is to be taken for several case labels, then we may write the
program as follows:
This is equivalent to:
if (letter==‘a’) || (letter==‘e’) ||
(letter==‘o’) || (letter==‘i’) ||
(letter==‘u’)
System.out.println (vowel);
63. 6
3
switch vs. nested if
The switch statement is an elegant way to apply multiple selections. It is less confusing.
However, the programmer is forced sometimes to use the nested if.
Examples of such cases include:
o If the selection involves a range of values.
Example: if (score >= 60) && (score < 70)
o If the selector’s type is double or float.
Example: if (salary == 5000.25)
66. Control Statements : Repetition statements
• Some times we need to repeat a specific course of actions either a specified number of times or
until a particular condition is being satisfied.
• For example :
– To calculate the Average grade for 10 students ,
– To calculate the bonus for 10 employees or
– To sum the input numbers from the user as long as he/she enters positive numbers.
• There are three methods by way of which we can repeat a part of a program. They are:
– (a) Using a while statement
– (b) Using a do-while statement
– (C) Using a for statement
66
67. 67
Opening Problem
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Problem
:
100
times
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
68. 68
1- The While Loop
1- loop counter is any numeric variable ( int , float ,….).
2- when using a counter , the while loop is called counter–controlled loop.
3- The initial value of the loop counter is up to you,
but you have to increment it to avoid endless loops.
While ( continuation condition)
{
Action statement 1 ;
Action statement 2 ;
.
.
Action statement n ;
}
69. 69
The condition being tested may be
relational, logical or even numeric
expression :
while ( i <= 10 )
while ( i >= 10 && j <= 15 )
While (3) , While (3 + 5)
70. • Example : Write a program that calculates and prints out the Average grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
while (counter <=6)
{
System.out.printf(" Enter grade for student no %d" , counter);
grade = input.nextInt( );
sum += grade;
counter ++;
}
System.out.printf(" Average Grade is %f“ , sum/counter );
70
71. • Example : Write a program that calculates and prints out the Average grade for 5 students or
ends the program by entering -1.
71
int grade=0, counter =1, sum=0;
System.out.println(" Enter 5 grades or -1 To Exit “);
while (counter <=5 && grade !=-1)
{
grade = input.nextInt( );
sum += grade;
counter ++;
}
System.out.printf(" The sum of grades is %d“,sum);
72. 72
Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts
the user to enter a number continuously until the number matches the randomly generated number. For
each user input, the program tells the user whether the input is too low or too high, so the user can choose
the next input intelligently. Here is a sample run:
76. 2- The do-while Loop
76
The condition being tested
may be relational, logical or
even numeric expression :
while ( i <= 10 )
while ( i >= 10 && j <= 15 )
While (3) , While (3 + 5)
77. • Example : Write a program that calculates and prints out the Average grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
do
{
System.out.println("Enter grade for student no “+ counter);
Grade= input.nextInt( );
sum += grade;
counter ++;
}
while (counter <=6) ;
System.out.println(" Average Grade is “ + sum/counter );
77
2- The do-While Loop
81. 3- The For Loop.
• For Loop is probably the most popular looping instruction.
• general form of for statement is
• The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) testing the loop counter to detect whether its value reached the number of repetitions desired.
(c) increasing the value of loop counter each time the program segment
within the loop has been executed.
82. • Example : Write a program that calculates and prints out the Average grade for 6 students .
82
int grade=0, sum=0;
for (int counter =1 ; counter <=6 ; counter ++)
{
System.out.println("Enter Grade “);
Grade = input.nextInt();
sum += grade;
}
System.out.println ("The Average grades is “ +( sum/6));
3- The For Loop.
int counter = 1;
int grade=0 , sum=0;
while (counter <=6)
{
System.out.println("Enter grade”) ;
grade = Input.nextInt( );
sum += grade;
counter ++;
}
System.out.println ("Average Grade is “ + (sum/6 );
83. 83
• Example : Write a program that prints out numbers from 0 to 10;
for (int i= 0 ; i <=10 ; i++)
System.out.println ( i );
• Example : Write a program that prints out the even numbers from 2 to
20;
for (int i = 2 ; i <=20 ; i+=2 )
System.out.println (i);
3- The For Loop.
• Example : Write a program that prints out numbers from 0 to 10 in
descending order;
for (int i = 10 ; i >=0 ; i-- )
System.out.println ( i);
84. 84
• Example : Write a program that accepts 10 numbers from the user and prints out the sum of even
numbers and the sum of odd numbers.
3- The For Loop.
85. 85
int i = 1 ;
for ( ; i <= 10 ; i + + )
System.out.println ( i);
int i = 1 ;
for ( ; i <= 10 ; )
{
System.out.println ( i);
i ++;
}
int i ;
for ( i = 0 ; i++ < 10 ; )
System.out.println ( i);
int i ;
for ( i = 0 ; ++ i < 10 ; )
System.out.println ( i);
86. • Example : Write a program that calculates the Factorial for any given positive number.
Ex : Factorial (5) = 5 * 4 * 3 * 2 * 1
86
int number, factorial=1;
System.out.println ( "Enter a positive number“);
Number = input.nextInt();
if (number < 0 )
System.out.println ( " Enter Positive Numbers only“) ;
else
for (int i= 1 ; i <=number ; i++)
factorial = factorial * i;
System.out.println ( " Factorial = “ + factorial);
3- The For Loop.
87. Nested Loops
• Example : Write a program that calculates the Factorial for numbers from 1 to 10;
87
for ( int number=1; number<=10 ; number++)
{
for ( int i= 1 ; i <=number ; i++)
{
factorial = factorial * i ;
}
System.out.println ( " Factorial = “ + factorial);
}
90. THE break STATEMENT
90
The break statement is typically used To exit early from a loop (for, while, do…while)
After the break statement, the remaining of the statements inside the loop are skipped. Then,
execution continues starting at the first statement after the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
Int num=0, counter = -1, sum = 0; //initialize the accumulator sum
while (counter <=5) //num is used as a sentinel
{
System.out.println (“Enter a positive integer”); //prompt
num = read.nextInt();
if (num < 0)
{
System.out.println (“Negative numbers are not allowed”);
break;
} //end if
sum =sum + num;
Counter ++;
} // end while
System.out.println (“Sum = “ + sum);
91. THE continue STATEMENT
91
The continue statement may be used in all loop statements (for, while, do…
while)
The continue statement skips the remaining statements inside the loop; and proceeds with
the next iteration, if any.
1
2
3
4
5
6
7
8
9
10
11
12
13
Int num=0, counter = -1, sum = 0; //initialize the accumulator sum
while (counter <=5) //num is used as a sentinel
{
System.out.println (“Enter a positive integer”); //prompt
num = read.nextInt();
if (num < 0)
{
System.out.println (“Negative numbers are not allowed”);
continue;
} //end if
sum =sum + num;
Counter ++;
} // end while
System.out.println (“Sum = “ + sum);
93. Java Programming For Beginners
Course 1
Revision on
Conditional and loop statements
94. 2. ANALYSIS
94
INPUT & OUTPUT
Saudi Airlines permit each passenger to hold one bag. The maximum
weight allowed for the bag depends on the class of the passenger
which is: 30 Kg for First class ('F'), 25 Kg for Business ('B') and 20 Kg
for Economy ('E'). If the weight of the bag excesses the allowed one,
the passenger should pay 10 SR for each Kg.
Write a program that calculates the excess baggage charge for the
passenger. All input data should be read by the user. Solve the
problem using the switch statement.
Charge depends on?
Passenger Class PassClass
(Given)
Allowed Weight
(Given)
First Class ‘F’ 30 Kg
Business Class ‘B’ 25 Kg
Econonmy Class ‘E’ 20 Kg
?
95. 2. ANALYSIS
95
INPUT
o Passenger’s Class Entered by the user.
o Baggage Weight Entered by the user.
OUTPUT
o Charge to excess weight:
• Excess weight = Actual Weight – Allowed Weight (depending on
his class)
• Charge = Excess Weight * 10 SR
For a specific passenger, we want to know:
101. Functions - Methods
• Most computer programs that solve real-world problems include hundreds and even thousands of lines.
• Experience has shown that the best way to develop and maintain a large program is to construct it from
smaller pieces or modules, each of which is more manageable than the original program.
• A Function : is a self-contained block of statements that perform a specific task.
• Using a function is something like hiring a person to do a specific job for you.
101
102. 102
Task 1
Task 2 Task 3
Task 4
Function ( )
Function ( ) Function ( )
Function ( )
In Real Life
In Programming
103. Why to use Functions ?
• Functions allows to write more manageable units of code.
• Writing functions avoids rewriting the same code over and over.
• Easy maintenance for programs.
Important Tips
1- Don’t try to cram the entire logic in one function. It is a very bad style of programming.
2- Instead, break a program into small units and write functions for each of these isolated subdivisions.
3- Don’t hesitate to write functions that are called only once.
103
104. 104
Task 1
Task 2 Task 3
Task 4
Get_Marks( )
Calc_sum( ) Calc_Average ( )
Print_out ( )
Calculate and print out The
sum and the Average of 3
student marks.
105. Functions
105
Function Definition
return-value-type function-name( parameter-list )
{
Lines of code to be
executed
…
(Body)
}
Parameter-List : Is a list of data values
supplied from the calling program as input to
the function. It is Optional
return-value- Type:
Is the data type for the returned value from the function to the
calling program. It is Mandatory, if no returned value
expected , we use keyword Void.
2- Invoking Function ( From The main( ) )
Function name ( Actual Parameter- List );
106. Function Types
1. Built in Functions (Ready Made).
• For Example : Math Functions Like
106
int abs (int number) ;
double pow (double base, double exponent) ;
Double floor (double number);
Double sqrt (double number);
108. User-Defined Functions
• Value-returning functions: have a return type
– Return a value of a specific data type using the return statement
– the returned value can be used in one of the following scenarios:
• Save the value for further calculation
Int result;
Result = sum ( x , y );
• Use the value in some calculation
Result = sum(x , y) /2;
• Print the value
System.out.println (sum(x , y) ) ;
• Void functions: do not have a return type
– Do not use a return statement to return a value
109. public class methodOneParameter
{
public static void main(String[] args)
{
System.out.println (“Start of Program”); //output line #1
drawLine(); //method calling
Sysetm.out.println(“Welcome to the First lecture in Functions”);
drawLine(); //method calling
System.out.println (“End of Program”);
} //end of main
//method definition: This method draws a line
public static void drawLine( )
{
int i;
for (i=0; i < 10; i++)
System.out.print (‘*’);
System.out.println();
} //end of drawLine
} //end of class
109
110. public class methodOneParameter
{
public static void main(String[] args)
{
System.out.println (“Start of Program”); //output line #1
drawLine(‘*’); //method calling
Sysetm.out.println(“Welcome to the First lecture in Functions”);
drawLine(‘#’); //method calling
System.out.println (“End of Program”);
} //end of main
//method definition: This method draws a line
public static void drawLine( char ch)
{
int i;
for (i=0; i < 10; i++)
System.out.print (ch);
System.out.println();
} //end of drawLine
} //end of class
110
111. public class methodOneParameter
{
public static void main(String[] args)
{
System.out.println (“Start of Program”); //output line #1
drawLine(‘*’,15); //method calling
Sysetm.out.println(“Welcome to the First lecture in Functions”);
drawLine(‘#’,20); //method calling
System.out.println (“End of Program”);
} //end of main
//method definition: This method draws a line
public static void drawLine(char ch , integer length )
{
int i;
for (i=0; i < length; i++)
System.out.print (ch);
System.out.println();
} //end of drawLine
} //end of class
111
114. 114
For Example : write a program that ask the user to Enter 3 integer numbers and print out their sum
and Average.
int main ()
{
int n1 , n2 , n3 ;
System.out.println("Please Enter 3 integer numbers “ );
n1= input.nextInt();
n2= input.nextInt();
n3= input.nextInt();
System.out.println(" The sum of the 3 number is “ || sum (n1, n2,n3) );
System.out.println(" The average of the 3 number is " || average (n1, n2,n3) );
}
Public static int sum (int num1 , int num2, int num3)
{
return num1+num2+num3;
}
Public static double average (int num1, int num2, int num3 )
{
return sum (num1 , num2 , num3)/3 ;
}
115. Scope of a variable
scope is the context within a program in which a variable is valid and can be used.
– Local variable: declared within a function (or block)
– can be accessible only within the function or from declaration to the end of the block.
– Within nested blocks if no variable with same name exists.
115
int main ( )
{
{
Int x ;
}
}
int sum (int x , int y )
{
int result ;
result = x + y;
return result;
}
Local
Local
116. Scope of a variable
Global variable: declared outside of every function definition.
– Can be accessed from any function that has no local variables with the same name. In case the
function has a local variable with the same name as the global variable ,
116
static Int z ;
int main ( )
{
{
}
}
int sum (int x , int y )
{
}
GLOBAL
117. 117
Static int x = 100 ;
int main ( )
{
int x= 10;
{
int z , x ;
z=100;
y=100;
x= 250;
System.out.println(" inner block " << x ;
}
}
Scope of a variable
GLOBAL
Local
Local
120. Method Overloading
120
Method Signature:
The signature of a method consists of the following:
Method name
Formal parameter list
Examples:
public int Sum(int x, int y)
public int Sum(int x, int y , int z)
public double Sum(double x, double y, double z)
public int Sum(int x, double y)
public int Sum(double y, int x)
Note that the method type is not part of its signature.
Method Overloading:
Defining several methods within a class with the same name. As long as every Method has
a different signature
121. 121
The following methods are incorrectly overloaded; the compiler generates an error:
public void methodABC (int x, double y)
public int methodABC (int x, double y)
public void methodABC (int x, double y)
public int methodABC (int num1, double num2)
Example (1): The following methods are incorrectly overloaded because they have the
same method name and same formal parameter lists:
Example (2): Changing the names of the formal parameters, does not allow overloading of
the previous counter-example:
public static void methodABC (int x, double y)
public int methodABC (int num1, double num2)
Counter-example (3): Adding the modifier static does not allow
overloading of the previous example:
Note that the method type and modifiers are not part of the overloading
rules
124. ARRAY DECLARATION
dataType[ ] arrayName = new datatype [intExp];
SYNTAX
In Java, an array is an object that must be instantiated using the new operator.
arrayName is the reference variable.
dataType is the data type of the array; which is the same type of all elements in the array.
intExp is any expression that evaluates to a positive int type.
intExp represents the size of the array: this is the number of elements in the array.
125. ARRAY DECLARATION
EXAMPLES
Consider the following array declaration:
int[] num = new int [5];
From the above statement:
o num is the array name
o num consists of 5 elements
o The type of the elements is int
The memory layout will be as follows:
Address Value
num 0
0
0
0
0
As shown, the array name points to the first element in the array.
The five elements of the array are adjacent in the memory.
Index
0
1
2
3
4
126. ARRAY DECLARATION
USING CONSTANTS AS SIZES
final int ARRAY_SIZE = 5;
int[] num = new int [ARRAY_SIZE];
double[ ] num = new double[ARRAY_SIZE];
char[ ] x = new char[ARRAY_SIZE];
boolean[ ] flags = new boolean[ARRAY_SIZE];
The size of the array must be of type int.
127. ARRAY DECLARATION
1
2
USING EXPRESSIONS AS SIZES
final int ARRAY_SIZE = 5;
int[] num = new int[ARRAY_SIZE*5];
The expression may be in terms of an int variable rather than a constant:
int i = 8;
int[] num = new int[i*2-1];
128. ARRAY DECLARATION
SPECIFYING SIZES DURING EXECUTION
Scanner read = new Scanner(System.in);
int arraySize;
System.out.println (“Enter the size of the array ”);
arraySize = read.nextInt();
int[ ] list = new int [arraySize];
It is not necessary to know the size of the array at compile time.
During program execution, the user may be prompted to enter the size of the
array. The object (array) is then instantiated using this value.
Consider the following example:
129. INITIALIZATION WITH DECLARATION
Double [ ] sales = {12.25, 24.2, 32.55, 50.33};
An array can also be initialized with specific values when it is
declared:
When initializing arrays during declaration, the size of the array is determined by the number
of initial values in the initializer list within the braces.
ARRAY Initialization
When instantiating an array object, the initial values depend on the array type:
o For numeric types (int, double, etc…) the elements take the value zero by
default.
o For char type, the elements take the value null character (‘’).
o For boolean type, the elements take the value false.
130. • Accessing array Elements
Arrayname [element index].
Arrays
• Example: int [] list = new list[10];
list[5] = 34;
System.out.println( list [5]);
131. • Example : Write a program that ask the user to enter 10 Employee salaries and store
them , then add a bonus of 10 % for each employee and print out the average salary value.
131
132. 132
Example - Write a program that finds the sum and the average of positive integers stored in an
array of integers.
134. Java Programming For Beginners
Course 1
One Dimensional Arrays – Part 2
Passing Arrays as a method
Parameters
135. Passing Array as a parameter to a
method
To pass an array argument to a method, specify the name of the array without any
brackets.
For example, if array ids is declared as
int [] ids = new int[50];
then the method call search ( ids , 100 );
passes the reference of array salaries to method search.
public static int search (int[] list, int target)
{
int index;
for (index = 0; index < list.length; index++)
if (list[index] == target);
return index;
return -1;
} //end search
Main()
{
Int [ ] employee_ids = new int[10];
Int position = Search(imployee_ids , 30);
}
136. public static void main(String[] args)
{
double[] sales = new double[100];
fillArray (sales);
printArray (sales);
}
public static void fillArray(double[ ] list)
{
for (int i=0; i<list.length; i++)
{
System.out.println (“Enter next element: “);
list[i] = read.nextDouble();
} //end for
} //end fillArray
public static void printArray(double[] list)
{
int i;
for (i=0; i < list.length; i++)
System.out.print (list[i] + “ “);
System.out.println();
} //end of printArray
Passing Array as a parameter to a
method
139. Two Dimensional Arrays
One-dimensional arrays are suitable for data provided in a list
form.
Two-dimensional arrays are suitable for data provided in a table
form.
CS1301 CS1111 PHY1040 CE1111
Fahd A A+ B B-
Ahmed A+ A- C B+
Faisal C+ D A- D+
For the above example, you need to know:
o The number of rows in the table (3 in the example)
o The number of columns in the table (4 in the example)
Also, in order to access an array element, you need to know:
o The element lies in which row and in which column
For example, Fahd grade in CE1111 lies in the intersection of the
first row with the fourth column.
100 120 135 145 190 210
Student_IDs
140. DECLARATION
rows : indicates the number of rows.
dataType[][] arrayName = new dataType[rows][cols];
SYNTAX
cols: indicates the number of columns.
The following example declares a two-dimensional array marks of 4 rows and 6 columns:
double[][] marks = new double[4][6];
142. length
Consider the following code segment:
Int [ ][ ] matrix = new int[20][15];
System.out.printf (“Number of rows = %d”, matrix.length);
System.out.printf (“Number of columns = %d”, matrix[0].length);
Number of rows = 20
Number of columns = 15
Output
arrayName.length gives the number of rows.
`gives the number of columns.
143. INITIALIZATION
The two-dimensional array may be initialized as follows:
//Initialize and declare
int[ ][ ] array2 = { {2, 1, 3}, {3, 5, 2}, {4, 2, 2}};
The above example may be depicted as follows:
2 1 3
3 5 2
4 2 2
144. Let us initialize the elements of row #2 to 7:
int col;
for (col = 0; col < matrix[2].length; col++)
matrix[2][col] = 7;
When processing a row using a loop, the condition is “the number of columns”, which is
matrix[2].length in this example.
The number of the row is fixed, and the number of the column varies from 0 to
matrix[2].length col is the loop counter.
Let us initialize the elements of col #1 to 5:
int row;
for (row = 0; row < matrix.length; row++)
matrix[row][1] = 5;
145. 145
• Example : Write a program that build a matrix of 5 rows and 3 columns . Ask the use to
enter the values for all the matrix items , print out the sum of all matrix items.
147. void printMatrix( int matrix[ ][4], int Rows)
{
int row, col;
for (row = 0; row < Rows ; row++)
{
for (col = 0; col < 4; col++)
System.out.println( setw(5) << matrix [row]
[col] ;
}
System.out.println(“n” ;
}
147
when declaring a two-dimensional array as a formal parameter, you can omit
the size of the first dimension, but not the second;
that is, you must specify the number of columns.
Two dimensional Array as a Parameter to
Function