0% found this document useful (0 votes)
21 views

Class 9

Uploaded by

artisanavenue8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Class 9

Uploaded by

artisanavenue8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

WELCOME TO

C PROGRAMMING
TUTORIAL
INDEX
S.NO TOPICS SUB TOPICS S.NO TOPICS SUB TOPICS
1.1 Introduction
5.1 History Of Java
1.2 IDE
5.2 Features Of Java
1 C BASICS 1.3 Quick Start
1.4 Syntax 5 JAVA INTRODUCTION 5.3 Why To Use Java
1.5 Output 5.4 Java Syntax
1.6 Comments 5.5 Java Working Method
2.1 Variables 5.6 Java Comments
2.2 Format Specifiers 6.1 Java Variables
2 C VARIABLES & DATA TYPES 2.3 Identifiers
6.2 Types Of Variables
2.4 Data Types VARIABLES & DATA
6 6.3 Datatypes
2.5 Constants TYPES
3.1 Operator Introduction 6.3.1 Primitive Datatypes
3.2 Arithmetic Operator 6.3.2 Non Primitive Datatypes
3.3 Assignment Operator 7.1 Loop Introduction
3 C OPERATOR
3.4 Comparison Operator 7.2 While Loop
3.5 Logical Operator JAVA LOOP CONTROL 7.3 For Loop
3.6 Sizeof Operator 7
7.4 Do While Loop
4.1 Introduction
7.5 Loop Control Statements
4.2 If Statement
4.3 Else Statement 7.6 Enhanced For Loop
4.4 If Else Staement 8.1 Java Class
4 C CONDITIONAL STATEMENTS
4.5 Switch 8.2 Object
4.6 While 8 JAVA CLASS 8.3 Java Class Attributes
4.7 Do While 8.3 Java Class Attributes
4.8 For Loop 8.4 Method
1. C BASICS
1.1 Introduction
What is C? Why Learn C?
• C is a general-purpose programming language • It is one of the most popular programming
created by Dennis Ritchie at the Bell language in the world.
Laboratories in 1972.
• If you know C, you will have no problem learning
• It is a very popular language, despite being old. other popular programming languages such as
Java, Python, C++, C#, etc, as the syntax is similar.
• C is strongly associated with UNIX, as it was
developed to write the UNIX operating system. • C is very fast, compared to other programming
languages, like Java and Python.

Difference between C and C++ • C is very versatile; it can be used in both


• C++ was developed as an extension of C, and applications and technologies.
both languages have almost the same syntax.
• C is very powerful; it has been used to develop
• The main difference between C and C++ is that operating systems, databases, applications, etc.
C++ support classes and objects, while C does
not.
1. C BASICS
1.2 IDE
Get Started With C :
TO START USING C, YOU NEED TWO THINGS: CODE :: BLOCK IDE
• A text editor, like Notepad, to write C code.
• A compiler, like GCC, to translate the C code into Let’s see program in Code :: Block IDE.
a language that the computer will understand.
You can find the latest version of Codeblocks at
• There are many text editors and compilers to http://www.codeblocks.org/.
• choose from.
Download the mingw-setup.exe file, which will
C Install IDE : install the text editor with a compiler.
• An IDE (Integrated Development Environment)
is used to edit AND compile the code. Open Codeblocks and go to File > New > Empty
• Popular IDE's include Code::Blocks, Eclipse, and File.
Visual Studio. These are all free, and they can be
used to both edit and debug C code. Write the C code and save the file as (Name of the
file).c (File > Save File as).
• Note: Web-based IDE's can work as well, but
functionality is limited.
1. C BASICS
How to communicate with computer?

A=10;
B=10;
C=A+B;
Print(C);

I/p
01010101010
10100100101 o/p
Complier 01001001000 Computer
1010100
1. C BASICS
1.3 Quick Start
C Quickstart : In Codeblocks, it should look like this:

Write the following C code and save


the file as myfirstprogram.c

Then, go to Build > Build and Run to run (execute) the program.
The result will look something to this:

We have now written and executed our first C program.


1. C BASICS
1.4 Syntax
Basics Tips for writing Programming In Codeblocks, it should look like this:
Language Line 1: #include <stdio.h> is a header file library that lets us work with
input and output functions, such as printf() (used in line 4). Header
• Every statement should end with files add functionality to C programs.
semicolon; Line 2: A blank line. C ignores white space. But we use it to make the
• Equal Curly braces{ }. code more readable.
Line 3: Another thing that always appear in a C program, is main(). This
• Must be Main () function.
is called a function. Any code inside its curly brackets {} will be
• Must be Header Files: executed.
#include<stdio.h>. Line 4: printf() is a function used to output/print text to the screen. In
our example it will output "Hello World".
#include <stdio.h> Note that: Every C statement ends with a semicolon ;
Note: The body of int main() could also been written as:
int main() { int main(){printf("Hello World!");return 0;}
printf("Hello World!"); Remember: The compiler ignores white spaces. However, multiple lines
return 0; makes the code more readable.
}
Line 5: return 0 ends the main() function.
Line 6: Do not forget to add the closing curly bracket } to actually end
the main function.
1. C BASICS
1.5 Output
Print Text : Multiple Printf() function:
Printf() function:
The print() function is used to output We can add as many printf() functions as you want.
values/print text. However, note that it does not insert a new line at the end of
the output.

Output: Output:
1. C BASICS
1.5 Output
C New Lines Multiple lines in single Printf() function:
To insert a new line, you can use the \ We can also output multiple lines with a single printf() function.
n character: However, be aware that this will make the code harder to read.

Output:
Output:
1. C BASICS
1.5 Output
Create Blank Line : What is \n exactly?
Two \n characters after each The newline character (\n) is called an escape sequence, and it
other will create a blank line. forces the cursor to change its position to the beginning of the next
line on the screen. This results in a new line.

Examples of other valid escape sequences are:

1. Escape Sequence Description


\t Creates a horizontal tab

Output:
Output:
1. C BASICS
1.5 Output
2. Escape Sequence Description 3. Escape Sequence Description
\\ Inserts a backslash character \" Inserts a double quote
(\) Character

Output: Output:
1. C BASICS
1.6 Comments
COMMENTS :
Comments can be used to explain code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.

Single-line Comments This example uses a single-line comment at the end of a


Single-line comments start with two line of code:
forward slashes (//).
Any text between // and the end of the line
is ignored by the compiler (will not be
executed).

Output:

Output :
1. C BASICS
1.6 Comments
C Multi-line Comments

• Multi-line comments start with /* and ends with */.


• Any text between /* and */ will be ignored by the compiler.

• Single or multi-line comments?

• It is up to you which you want to use. Normally,


• we use // for short comments, and /* */ for longer.

• Before version C99 (released in 1999), you could only


• use multi-line comments in C.

Output :
2. C Variables & Data Types
2.1 Variables
C Variables :
• Variables are containers for storing data values.
• In C, there are different types of variables (defined with different keywords).
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

Declaring (Creating) Variables So, to create a variable that should store


To create a variable, specify the type and a number, look at the following example:
assign it a value.
Create a variable called myNum of type
Syntax int and assign the value 15 to it:

Where type is one of C types (such as int), and


variableName is the name of the variable (such as
x or myName). The equal sign is used to assign a
value to the variable.
2. C Variables & Data Types
2.1 Variables
We can also declare a variable without In many other programming languages (like
assigning the value, and assign the value later. Python, Java, and C++), We would normally use a
print function to display the value of a variable.
However, this is not possible in C.
In many other programming languages (like Example :
Python, Java, and C++), We would normally use a
print function to display the value of a variable.
However, this is not possible in C:
Example :

Output :
Note: If you assign a new value to an existing
variab le, it will overwrite the previous value:
Example :
To output variables in C, you must get familiar with
something called "format specifiers".
2. C Variables & Data Types
2.1 Variables

Add Variables Together :

To add a variable to another variable, you can use the + operator:

Output :
2. C Variables & Data Types
2.1 Variables

Declare Multiple Variables”

To declare more than one variable of the same type, use a comma-separated list.

Example:

Output :
2. C Variables & Data Types
2.1 Variables
We can also assign the same value to multiple variables of the same
type.

Example:

Output :
2. C Variables & Data Types
2.1 Variables

C Variable Names

• All C variables must be identified with unique names.


• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age, sum, total
Volume).
• Note : It is recommended to use descriptive names in order to create understandable and
maintainable code.

Example :
2. C Variables & Data Types
2.1 Variables
The general rules for naming variables are:

• Names can contain letters, digits and underscores.

• Names must begin with a letter or an underscore (_).

• Names are case sensitive (myVar and myvar are different variables).

• Names cannot contain whitespaces or special characters like !, #, %, etc.

• Reserved words (such as int) cannot be used as names.


2. C Variables & Data Types
2.2 Format Specifiers
Format Specifiers:
Format specifiers are used together with the printf() function to tell the compiler what type
of data the variable is storing. It is basically a placeholder for the variable value.
A format specifier starts with a percentage sign %, followed by a character.

To output the value of an int variable, To print other types, use %c for char and %f for float:
you must use the format specifier %d or
%i surrounded by double quotes, inside
the printf() function.

Example: Output :

Output :
2. C Variables & Data Types
2.2 Format Specifiers

To combine both text and a variable, To print different types in a single printf()
separate them with a comma inside the printf() function, you can use the following.
function:
Example
Example:

Output :
Output :
2. C Variables & Data Types
2.3 Identifiers

C Identifiers :

C identifiers represent the name in the C program, for example, variables,


functions, arrays, structures, unions, labels, etc.
An identifier can be composed of letters such as uppercase, lowercase letters,
underscore, digits, but the starting letter should be either an alphabet or an underscore.
If the identifier is not used in the external linkage, then it is called as an internal
identifier. If the identifier is used in the external linkage, then it is called as an external
identifier.
We can say that an identifier is a collection of alphanumeric characters that
begins either with an alphabetical character or an underscore, which are used to represent
various programming elements such as variables, functions, arrays, structures, unions,
labels, etc.
There are 52 alphabetical characters (uppercase and lowercase), underscore
character, and ten numerical digits (0-9) that represent the identifiers. There is a total of 63
alphanumerical characters that represent the identifiers.
2. C Variables & Data Types
2.3 Identifiers
Rules for constructing C identifiers:
• The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.

• It should not begin with any numerical digit.

• In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.

• Commas or blank spaces cannot be specified within an identifier.

• Keywords cannot be represented as an identifier.

• The length of the identifiers should not be more than 31 characters.

• Identifiers should be written in such a way that it is meaningful, short, and easy to read.

• Ex total, sum, average, _m _, sum_1, etc.


2. C Variables & Data Types
2.4 Data Types
C Data Types :

A variable in C must be a specified data type, and you must use a format specifier inside the
printf() function to display it .

Output :
2. C Variables & Data Types
2.4 Data Types
Basic Data Types :

The data type specifies the size and type of information the variable will store.
2. C Variables & Data Types
2.4 Data Types
Basic Data Types :

The data type specifies the size and type of information the variable will store.
2. C Variables & Data Types
2.4 Data Types
Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them.

Format Specifier Data Type

%d or %i int

Output :
2. C Variables & Data Types
2.4 Data Types
Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them.

Format Specifier Data Type

%f float

Output :
2. C Variables & Data Types
2.4 Data Types
Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them.

Format Specifier Data Type

%lf double

Output :
2. C Variables & Data Types
2.4 Data Types
Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them.

Format Specifier Data Type

%c char

Output :
2. C Variables & Data Types
2.4 Data Types
Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them.

Format Specifier Data Type

%s Used for strings

Output :
2. C Variables & Data Types
2.5 Constants
Constants
When we don't want others (or yourself) to override existing variable values, use the const
keyword (this will declare the variable as "constant", which means unchangeable and read-only).

Output :
2. C Variables & Data Types
2.5 Constants

We should always declare the variable as constant when you have values that are unlikely to change
When we don't want others (or yourself) to override existing variable values, use the const keyword (this
will declare the variable as "constant", which means unchangeable and read-only).

Example: Output :
2. C Variables & Data Types
2.5 Constants
Notes On Constants

When you declare a constant variable, it must be assigned with a value.


Example

This however, will not work:


const int minutesPerHour; Output :
minutesPerHour = 60; // error
3. C Operator
3.1 Operator Introduction
C Operators :
• Operators are used to perform operations on variables and values.

• In the example below, we use the + operator to add together two value.

Example :

Output :
3. C Operator
3.1 Operator Introduction

Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable.

Example
Output :
3. C Operator
3.1 Operator Introduction
C divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
3. C Operator
3.2 Arithmetic Operator

Addition Operator : Subtraction Operator : Multiplication Operator :


3. C Operator
3.2 Arithmetic Operator

Division Operator Modulus Operator Increment Operator Decrement Operator


3. C Operator
3.3 Assignment Operators
Assignment Operators :
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x.
The addition assignment operator
(+=) adds a value to a variable

Example :

Output :
3. C Operator
3.4 Comparison Operator
Comparison Operators
Comparison operators are used to compare two values.
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example :

Output :
3. C Operator
3.5 Logical Operator
Logical Operators
Logical operators are used to determine the logic between variables or values
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3.

Example :

Output :
3. C Operator
3.6 Sizeof Operator

Sizeof Operator

The memory size (in bytes) of a data type or a variable can be found with the sizeof operator.

Example :
Output :
4. C CONDITIONAL STATEMENTS
4.1 INTRODUCITON

C has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true.

• Use else to specify a block of code to be executed, if the same condition is false.

• Use else if to specify a new condition to test, if the first condition is false.

• Use switch to specify many alternative blocks of code to be executed.


4. C CONDITIONAL STATEMENTS
4.2 IF STATEMENT

The if Statement:

Use the if statement to specify a block of C code to be executed if a condition is true.

Syntax :

Note :
That if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
4. C CONDITIONAL STATEMENTS
4.2 IF STATEMENT

Example :

we test two values to find out if 20 is greater than 18. If the condition is true, print some
text.

Output :
4. C CONDITIONAL STATEMENTS
4.3 ELSE STATEMENT

The else Statement

Use the else statement to specify a block of code to be executed if the condition is
false.

Syntax : Example

Output Output :
4. C CONDITIONAL STATEMENTS
4.4 IF ELSE STATEMENT

The if else Statement :


Use the else if statement to specify a new condition if the first condition is false.

Syntax :
Example

Output
Output :
4. C CONDITIONAL STATEMENTS
4.4 IF ELSE STATEMENT
C Short Hand If Else (Ternary Operator) :
There is also a short-hand if else, which is known as the ternary operator because it consists
of three operands. It can be used to replace multiple lines of code with a single line. It is often used to
replace simple if else statements.

Syntax : Example : Output :

It is completely up to us if we want to use the traditional if...else statement or the ternary operator.
4. C CONDITIONAL STATEMENTS
4.5 Switch
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed.

Syntax : This is how it works:


 The switch expression is evaluated once
 The value of the expression is compared with
the values of each case
 If there is a match, the associated block of
code is executed
 The break statement breaks out of the switch
block and stops the execution
 The default statement is optional, and specifies
some code to run if there is no case match.
4. C CONDITIONAL STATEMENTS
4.5 Switch
Switch Statement :

Output :
4. C CONDITIONAL STATEMENTS
4.6 While
Loops:
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.

While Loop
The while loop loops through a block of code as long as a specified condition is true.

Syntax :

Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never
end!
4. C CONDITIONAL STATEMENTS
4.6 While

In the example below, the code in the loop will run, over and over again, as long as a variable (i)
is less than 5.

The while loop loops through a block of code as long as a specified condition is true.

Syntax : Output :
4. C CONDITIONAL STATEMENTS
4.7 DO WHILE
The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.

Syntax :

Do not forget to increase the variable used in the condition, otherwise the loop will never end!C
4. C CONDITIONAL STATEMENTS
4.7 DO WHILE

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition
is false, because the code block is executed before the condition is tested.

Example : Output:
4. C CONDITIONAL STATEMENTS
4.8 FOR LOOP
For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop.

Syntax :  Statement 1 is executed (one time) before the


execution of the code block.
 Statement 2 defines the condition for executing
the code block.
 Statement 3 is executed (every time) after the
code block has been executed.

Do not forget to increase the variable used in the condition, otherwise the loop will never end!
4. C CONDITIONAL STATEMENTS
4.8 FOR LOOP

The example below will print the numbers 0 to 4.

Example : Output: Explanation :

 Statement 1 sets a variable before the


loop starts (int i = 0).
 Statement 2 defines the condition for
the loop to run (i must be less than 5).
If the condition is true, the loop will
start over again, if it is false, the loop
will end.
 Statement 3 increases a value (i++)
each time the code block in the loop
has been executed.
5. JAVA INTRODUCTION
5.1 HISTORY OF JAVA

 JAVA was developed by James gosling, who is known as


the father of java, in 1995. James gosling and his team
members started the project in the early '90s.

 Currently, java is used in internet programming, mobile


devices, games, e-business solutions, etc. Following are
given significant points that describe the history of java.

 It is owned by oracle, and more than 3 billion devices run


java.
5. JAVA INTRODUCTION
5.2 FEATURES OF JAVA
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
And much, much more!
5. JAVA INTRODUCTION
5.3 WHY TO USE JAVA ?

 Java works on different platforms (windows, mac, Linux, raspberry pi, etc.)
 It is one of the most popular programming language in the world
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As java is close to C++ and C#, it makes it easy for programmers to switch
to java or vice versa
5. JAVA INTRODUCTION
5.4 JAVA SYNTAX
Main () Println()
 The main() method is required and you will Inside the main() method, we can use
see it in every java program: the println() method to print a line of text to the
screen:
 Public static void main(string[] args)
Public static void main(string[] args)
 Any code inside the main() method will be {
executed. System.out.Println("hello world");
 Just remember that every java program has }
a class name which must match the filename,
and that every program must contain
the main() method.
5. JAVA INTRODUCTION
5.4 JAVA SYNTAX

• In java, every application begins with a class  Every line of code that runs in java must be inside
name, and that class must match the filename. a class. In our example, we named the class main.
• Let's create our first java file, called main.Java, A class should always start with an uppercase
which can be done in any text editor (like first letter.
notepad).  Note: java is case-sensitive: "myclass" and
"myclass" has different meaning.
The file should contain a "hello world" message,  The name of the java file must match the class
which is written with the following code: name. When saving the file, save it using the class
Public class main { name and add ".Java" to the end of the filename.
Public static void main(string[] args) { To run the example above on your computer,
System.Out.Println("hello world"); make sure that java is properly installed.
}
}
5. JAVA INTRODUCTION
5.5 JAVA WORKING METHOD
Java Comments 5. JAVA INTRODUCTION
5.6 JAVA COMMENTS

 Comments can be used to explain java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
 Single-line comments start with two forward slashes (//).
 Any text between // and the end of the line is ignored by java (will not be
executed).
 Multi-line comments start with /* and ends with */.
 Any text between /* and */ will be ignored by java.
 It is up to you which you want to use. Normally, we use // for short comments,
and /* */ for longer.
6. VARIABLES & DATA TYPES
6.1 JAVA VARIABLES

Variables are containers(Memory Area) for storing data values.

A B C

Personal
Clothes Vegetables belongings

String – stores text, such as “Hello”. String values are surrounded by double quotes
int – stores integers (whole numbers), without decimals, such as 123 or -123
float – stores floating point numbers, with decimals, such as 19.99 or -19.99
char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single
quotes
Boolean – stores values with two states: true or false
6. VARIABLES & DATA TYPES
6.2 TYPES OF VARIABLES

 Int - stores integers (whole numbers), without public class Main {


decimals, such as 123 or -123 public static void main(String[] args) {
int myNum = 5; // integer (whole
 String – stores text, such as “hello”. String number)
values are surrounded by double quotes float myFloatNum = 5.99f; // floating point
number
 Float – stores floating point numbers, with char myLetter = 'D'; // character
decimals, such as 19.99 or -19.99 boolean myBool = true; // boolean
String myText = "Hello"; // String
 Char – stores single characters, such as ‘a’ or System.out.println(myNum);
‘B’. Char values are surrounded by single System.out.println(myFloatNum);
quotes System.out.println(myLetter);
System.out.println(myBool);
 Boolean – stores values with two states: true System.out.println(myText);
or false }
}
6. VARIABLES & DATA TYPES
6.3 DATA TYPES
This presentation is to aware you about the java data types.
The data types are divided into two groups.
 Primitive data types – (java numbers, java scientific number, java
Boolean data types and java character)
 Non – primitive data types.
6. VARIABLES & DATA TYPES
6.3.1 PRIMITIVE DATA TYPES
Data Type Size Description
Stores whole numbers from
byte 1 byte
-128 to 127.
Stores whole numbers from PRIMITIVE DATA TYPE :
short 2 bytes
-32768 to 32767.
Stores whole numbers from A primitive data type specifies
int 4 bytes
-2,147,483,648 to 2,147,483,648.
the size and type of variable
Stores whole numbers from values, and it has no
long 8 bytes -9,223,372,036,854,775,808 to additional methods. There are
9,223,372,036,854,775,807
eight primitive data types in
Stores fractional numbers. java .
float 4 bytes Sufficient for storing 6 to 7 decimal
digits.

Stores fractional numbers. Sufficient


double 8 bytes
for storing 15 decimal digits.

boolean 1 bit Stores true or false values.


Stores a single character/letter or
char 2 bytes
ASCII values.
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

JAVA NUMBERS

Primitive number types are divided into two groups:

Even though there are many numeric types in java, the most used for numbers are int (for whole numbers)
and double (for floating point numbers).

1. Integer types - stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid
types are byte, short, int and long. Which type you should use, depends on the numeric value.

2. Floating point types - represents numbers with a fractional part, containing one or more decimals. There are
two types:float and double.
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers
INTEGER TYPES :

1.Byte
The byte data type can store whole numbers from -128 to 127. This
can be used instead of int or other integer types to save memory when
you are certain that the value will be within -128 and 127.
Example:-
Byte mynum = 100;
System.Out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

INTEGER TYPES :

2.Short
The Short Data Type Can Store Whole Numbers
From -32768 To 32767.
Example:-
Short Mynum = 5000;
System.out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

INTEGER TYPES :

3.Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the
preferred data type when we create variables with a numeric value.
Example:-
Int mynum = 100000;
System.Out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

INTEGER TYPES :

4.Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an “L”.
Example:-
Long mynum = 15000000000L;
System.Out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

Floating Data types


 We should use a floating point type whenever you
need a number with a decimal, such as 9.99 or 3.14515.
 the float and double data types can store fractional
numbers. note that you should end the value with an "f" for
floats and "d" for doubles:

FLOAT TYPES :

1.Float
Example:-
Float mynum = 5.75f;
System.Out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.1 Java numbers

FLOAT TYPES :

2.double
Example:-
Double mynum = 19.99d;
System.Out.Println(mynum);
6. VARIABLES & DATA TYPES
6.3.1.3 BOOLEAN TYPES

Boolean types
A boolean data type is declared with
the boolean keyword and can only taken
the values true or false.

Example:-
Boolean isjavafun = true;
Boolean isfishtasty = false;
System.Out.Println(isjavafun);
System.Out.Println(isfishtasty);
6. VARIABLES & DATA TYPES
6.3.1.4 JAVA CHARACTERS

Character
The char data type is used to store a single character.
The character must be surrounded by single quotes, like
‘a’or‘c’.
Example:-
Char mygrade = 'B’;
System.Out.Println(mygrade);
6. VARIABLES & DATA TYPES
6.3.1.4 JAVA CHARACTERS

String
The string data type is used to store a sequence of
characters (text). String values must be surrounded by
double quotes .
Example:-
String greeting = "hello world";
system.out.Println(greeting);
6. VARIABLES & DATA TYPES
6.3.2 Non - primitive data types

 Non-primitive data types are called reference types because they refer to objects.
 The main difference between primitive and non-primitive data types are:
 Primitive types are predefined (already defined) in java. Non-primitive types are created by the
programmer and is not defined by java (except for string).
 Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase
letter.
 The size of a primitive type depends on the data type, while non-primitive types have all the same size.
 Examples of non-primitive types are strings, arrays, classes, interface, etc.
7. JAVA LOOP CONTROL
Java

7.1 Loop Introduction


▪ There may be a situation when you need to execute a block of code several number of times. In general, statements
are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
▪ Programming languages provide various control structures that allow for more complicated execution paths.
▪ A loop statement allows us to execute a statement or group of statements multiple times and following is the
general form of a loop statement in most of the programming languages:

Loop Type Description

while loop Repeats a statement or group of statements while a given


condition is true. It tests the condition before executing the
loop body.

for loop Execute a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at
the end of the loop body.
Java

7. JAVA LOOP CONTROL


7.2 WHILE LOOP
A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.

syntax : while(Boolean_expression)
{
//Statements
}

• Here, statement(s) may be a single statement or a block


of statements.
• Thecondition may be any expression, and true is any non
zero value.
• When executing, if the boolean_expression result is true,
then the actions inside the loop will be executed. This
will continue as long as the expression result is true.
• When the condition becomes false, program control
passes to the line immediately following the loop.
7. JAVA LOOP CONTROL
7.2 WHILE LOOP
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.

public class Test { This will produce the following result:

public static void main(String args[]) { int x = value of x : 10


10; value of x : 11
value of x : 12
while( x < 20 ) { value of x : 13
System.out.print("value of x : " + x ); x++;
System.out.print("\n"); value of x : 14
} value of x : 15
}
} value of x : 16
value of x : 17
value of x : 18
value of x : 19
7. JAVA LOOP CONTROL
7.3 FOR LOOP

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be
executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

Syntax

for(initialization; Boolean_expression; update)


{
//Statements
}
7. JAVA LOOP CONTROL
7.3 FOR LOOP

Here is the flow of control in a for loop:


• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables and this step ends with a semi colon (;).

• Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop will not be executed and control jumps to the next statement past
the for loop.

• After the body of the for loop gets executed, the control jumps back up to the update statement.
This statement allows you to update any loop control variables. This statement can be left
blank with a semicolon at the end.

• The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
7. JAVA LOOP CONTROL
7.3 FOR LOOP

Flow Diagram Example


Following is an example code of the for loop in Java.

public class Test {


public static void main(String args[])
{ for(int x = 10; x < 20; x = x+1)
{
System.out.print("value of x :
" + x ); System.out.print("\
n");
}
}
}
Java

7. JAVA LOOP CONTROL


7.3 FOR LOOP

This will produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
7. JAVA LOOP CONTROL
7.4 Do While LOOP
• A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

Syntax
Following is the syntax of a do...while loop:

do
{
//Statements
}while(Boolean_expression);

• Notice that the Boolean expression appears at the end of the loop, so the statements in
the loop execute once before the Boolean is tested.
• If the Boolean expression is true, the control jumps back up to do statement, and the
statements in the loop execute again. This process repeats until the Boolean
expression is false.
7. JAVA LOOP CONTROL
7.4 Do While LOOP

public class Test {


Result
public static
void value of x : 10
value of x : 11
main(String value of x : 12
args[]){ int x value of x : 13
value of x : 14
= 10; value of x : 15
value of x : 16
value of x : 17
do{ value of x : 18
System.out.print
("value of x : " value of x : 19
+ x ); x++;
System.out.print("\n");
}while( x < 20 );
}
}
7. JAVA LOOP CONTROL
7.5 Loop Control Statements
• Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
• Java supports the following control statements. Click the following links to check
their detail.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.

continue statement Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
7. JAVA LOOP CONTROL
7.5.1 BREAK STATEMENT

Break Statement in Java

• The break statement in Java programming language has the following


two usages:
• When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.

• It can be used to terminate a case in the switch statement.


Java

7. JAVA LOOP CONTROL


7.5.1 BREAK STATEMENT

public class Test {

public static void main(String args[])


Result
{ int [] numbers = {10, 20, 30, 40,
50}; 10
20

for(int x : numbers ) { if( x ==


30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Java

7. JAVA LOOP CONTROL


7.5.2 Continue Statement in Java

• The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes control to immediately jump to the update
statement.
• In a while loop or do/while loop, control immediately jumps to the Boolean expression.

Expression: This evaluates to the array you need to


loop through. The expression can be an array
variable or method call that returns an array.
Java

7. JAVA LOOP CONTROL


7.5.2 Continue Statement in Java

public class Test {

public static void main(String Result


args[]) { int [] numbers =
10
{10, 20, 30, 40, 50};
20
40
for(int x : numbers ) 50
{ if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\
n");
}
}
}
7. JAVA LOOP CONTROL
7.6 Enhanced for loop in Java
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements
including arrays.

Syntax
for(declaration : expression)
{
//Statements
}

Declaration: The newly declared block variable, is of a type compatible with the elements of the array you are
accessing. The variable will be available within the for block and its value would be the same as the current array
element.
Java

7. JAVA LOOP CONTROL


7.5 Enhanced for loop in Java
public class Test {

public static void main(String args[]){ int [] numbers


Result
= {10, 20, 30, 40, 50};
10,20,30,40,50,
for(int x : numbers ){ System.out.print( x ); James,Larry,Tom,Lacy,

System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
8 .Java Classes/Objects
8.1 Class
• Java is an object-oriented programming language.
• Everything in Java is associated with classes and objects, along with its attributes and methods.
• For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods,
• such as drive and brake.
• A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

public class Main


{
int x = 10;
}
8 .Java Classes/Objects
8.2 Object

• In Java, an object is created from a class. We have already created the class named Main,

• so now we can use this to create objects.To create an object of Main, specify the class name,
followed by the object name, and use the keyword new.

Create an object called "myObj" and print the value of x:

public class Main


{
int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
8 .Java Classes/Objects
8.3 Java Class Attributes
Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown below). It is
actually an attribute of the class. Or you could say that class attributes are variables within a class.

Create a class called "Main" with two attributes: x and y:

public class Main


{
int x = 5;
int y = 3;

}
8 .Java Classes/Objects
8.3 Java Class Attributes
Accessing Attributes
We can access attributes by creating an object of the class, and by using the dot syntax (.):

The following example will create an object of the Main class, with the name myObj. We use
the x attribute on the object to print its value.

Create an object called "myObj" and


print the value of x:

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
8 .Java Classes/Objects
8.3 Java Class Attributes

Modify Attributes
public class Main {
int x = 10;
You can also modify attribute values
public static void main(String[] args) {
Main myObj = new Main();
If you don't want the ability to override myObj.x = 25; // x is now 25
existing values, declare the attribute System.out.println(myObj.x);
as final: }
}
The final keyword is called a "modifier"
8 .Java Classes/Objects
8.3 Java Class Attributes

8.6 Multiple Objects

If you create multiple objects of one class, you can change the attribute values in
one object, without affecting the attribute values in the other.

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25; System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
}
8 .Java Classes/Objects
8.3 Java Class Attributes

8.7 Multiple Attributes

You can specify as many attributes as you want:

public class Main {


String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
8 .Java Classes/Objects
8.4 Methods

• A method is a block of code that only runs when it is called.


• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known
as functions.

Why use methods?


To reuse code: define the code once, and use it many times.

Create a Method
• A method must be declared within a class.

• It is defined with the name of the method, followed by parentheses ().

• Java provides some pre-defined methods, such as System.out.println(),

• But you can also create your own methods to perform certain actions:
8 .Java Classes/Objects
8.4 Methods

public class Main { Example Explained:


• myMethod() is the name of the method
static void myMethod() { • static means that the method belongs to the Main
class and not an object of the Main class. You will
// code to be executed } learn more about objects and how to access methods
} through objects later in this tutorial.
• void means that this method does not have a
return value.
8 .Java Classes/Objects
8.4 Method
CALL A METHOD :
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called.

public class Main { public class Main {


static void myMethod() {
static void myMethod() { System.out.println("I just got
executed!");
System.out.println("I just got }
executed!"); public static void main(String[] args) {
} myMethod();
public static void main(String[] myMethod();
args) { myMethod();
myMethod(); }
} }
}
8 .Java Classes/Objects
8.4 Method
Static vs. Non-Static
• We will often see Java programs that have either static or public attributes and methods.
• In the example above, we created a static method, which means that it can be accessed without creating an
object of the class, unlike public, which can only be accessed by objects.

public class Main {


// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects"); }
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects"); }
// Main method
public static void main(String[] args) { myStaticMethod();
// Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
8 .Java Classes/Objects
8.4 Method
Create a Car object named myCar. Call the fullThrottle() and speed() methods on the myCar object, and run the
program:

// Create a Main class


public class Main {
// Create a fullThrottle() method
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}
// Create a speed() method and add a parameter
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
// Inside main, call the methods on the myCar object
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle()
method myCar.speed(200); // Call the speed() method
}
} // The car is going as fast as it can! // Max speed is: 200
8 .Java Classes/Objects
8.4 Method
Example explained
1) We created a custom Main class with the class keyword.
2) We created the fullThrottle() and speed() methods in the Main class.
3) The fullThrottle() method and the speed() method will print out some text, when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that runs your
program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program
using the name of the object (myCar), followed by a dot (.), followed by the name of the method
(fullThrottle(); and speed(200);). Notice that we add an int parameter of 200 inside
the speed() method.

Remember that..
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a
semicolon (;).
A class must have a matching filename (Main and Main.java).
This presentation and any files attached and/or transmitted with it are
confidential and intended solely for the use of the individual or entity to
whom they are addressed. No part of this presentation may be given,
lent, resold, or disclosed to any unintended recipients or exploited for
any commercial purposes. If you are not the intended recipient and
you have received this presentation in error, please return this material
to the sender immediately and forthwith delete and destroy the
presentation including any copies thereof from your records. We
hereby notify that disclosing, distributing, copying, reproducing, storing
in a retrieval system, or transmitting in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, or
taking any action in reliance on the contents of the presentation in its
entirety or any part thereof is strictly prohibited without the prior written
consent of WNS, such consent being given at the sole discretion of
WNS. Any views or opinion expressed in this presentation are those of
the author and do not necessarily represent that of WNS. WNS makes
no representations and to the full extent permissible by applicable law,
WNS disclaims any warranties of any kind, express or implied,
including any warranty of merchantability, accuracy, fitness or
applicability for a particular purpose, and non-infringement of third
party rights, as to the information, content and materials.

wnscaresfoundation.org
110 © Copyright 2020 WNS (Holdings) Ltd. All rights reserved

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy