02 - Programming Fundamentals Part1
02 - Programming Fundamentals Part1
in Java I
Instructor: Dr. Fahed Jubair
Let us Start with A Demo
y = x + 22 ; % modulus
++ increment
z = 4.4 * 5.3 / x ;
−− decrement
x++ ;
--y;
© All rights reserved. 6
Increment and Decrement Statements
Bitwise Operators
int x = 10;
& Bitwise and
int y = 13; | Bitwise OR
boolean z = x || y ; || logical OR
! Logical not
System.out.println(z);
if ( 𝑖 % 2 == 0 )
if ( 𝑥 > 100 ) System.out.println(“even number”);
System.out.println(“larger than 100”); else
System.out.println(“odd number”);
Assignment Operators
𝐴 == 𝐵 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑒𝑞𝑢𝑎𝑙 𝑡𝑜 𝐵
𝐴!=𝐵 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑛𝑜𝑡 𝑒𝑞𝑢𝑎𝑙 𝑡𝑜 𝐵
𝐴>𝐵 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑙𝑎𝑟𝑔𝑒𝑟 𝑡ℎ𝑎𝑛 𝐵
𝐴<𝐵 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑠𝑚𝑎𝑙𝑙𝑒𝑟 𝑡ℎ𝑎𝑛 𝐵
A >= B 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑙𝑎𝑟𝑔𝑒𝑟 𝑡ℎ𝑎𝑛 𝑜𝑟 𝑒𝑞𝑢𝑎𝑙 𝑡𝑜 𝐵
A <= B 𝑟𝑒𝑡𝑢𝑟𝑛 𝑡𝑟𝑢𝑒 𝑖𝑓 𝐴 𝑖𝑠 𝑠𝑚𝑎𝑙𝑙𝑒𝑟 𝑡ℎ𝑎𝑛 𝑜𝑟 𝑒𝑞𝑢𝑎𝑙 𝑡𝑜 𝐵
Question: how to force the else statement to match the first clause?
e.g.,
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
int sum = 0 ;
for ( 𝑖 = 0; 𝑖 <= 100; 𝑖 + + )
for ( 𝑗 = 0; 𝑗 <= 𝑖; 𝑗 + + )
sum = sum + 𝑖 ∗ 𝑗 ;
int sum = 0 ;
int sum = 0 ; int k = 1 ;
for ( 𝑖 = 0; 𝑖 <= 15; 𝑖 + + ) { while ( 𝑘 < 100) {
if ( 𝑖%3 == 0) sum += 𝑘 * 2;
continue ; if ( sum > 20)
sum += 𝑖 ; break ;
} ++k ;
System.out.println(sum); }
System.out.println(𝑘);
2. Write a java program that prints all square numbers up to 10000, i.e.,
1, 4, 9, 16, 25, 36, …, 10000
3. Write a java program that uses loops to print all positive integer pairs
x and y that satisfy the inequality: 2 ∗ 𝑥 + 3 ∗ 𝑦 ≤ 60
* * *
** ** **
*** *** ***
**** ****
***** *****
******
*******
********
© All rights reserved. 25
Classroom Exercise: Zodiac Year
5. Write a program that prompts the user to enter a year and displays the
animal for the year.