Easy Basics: Conditions & Loops in Java – Animation & Gaming
Easy
(Basics: Conditions & L )
1.
Bus Ticket Counter
Story:
A conductor issues tokens to passengers. Each passenger must get a number in
sequence.
Why: Helps students learn loops.
Logic:
- Input: number of passengers.
- Use for loop to print numbers 1 to n.
- Extension: use if
inside loop to print only even tokens.
Program:
import java.util.Scanner;
public class program1 {
public static void main(String[] args){
int a;
Scanner gopi= new Scanner(System.in);
System.out.println("enter the no of passengers:");
int n=gopi.nextInt();
for(a=2;a<=n;a+=3)
System.out.println("Odd no of passengers:"+a);
}
}
Output:
2.
Shop Discount Calculator
Story:
A shop applies discounts depending on bill amount.
Why: Introduces if-else conditions.
Logic:
- Input: bill amount.
- If bill < 1000 → apply 10%.
- Else → apply 20%.
- Final price = bill - discount.
Program :
import java.util.Scanner;
public class program2
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
float discount=0;
System.out.println("Enter the bill amount:");
int amount=sc.nextInt();
if(amount<1000)
{
discount=amount*10/100;
}
else
{
discount=amount*20/100;
}
float price=amount-discount;
System.out.println("final price:"+ price);
}
}
Output:
3. School Attendance
Story:
Class teacher records attendance as "P" for present, "A" for absent.
Why: Helps in counting characters in a string.
Logic:
- Input: string like "PAPAPPPAA".
- Loop through string → count P and A.
- Print "Present = X, Absent = Y".
Program :
import java.util.Scanner;
public class program3{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the attendance:");
String attendance = sc.nextLine();
int presentCount = 0;
int absentCount = 0;
for (int i = 0; i < attendance. Length(); i++) {
char ch = attendance.charAt(i);
if (ch == 'P') {
presentCount++;
} else if (ch == 'A') {
absentCount++;
}
}
System.out.println("Total Attendance - Present: " + presentCount + ", Absent: " + absentCount);
sc.close();
}
}
Output :
import java.util.Scanner;
public class program3{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the attendance:");
String attendance = sc.nextLine();
int presentCount = 0;
int absentCount = 0;
for (int i = 0; i < attendance.length(); i++) {
char ch = attendance.charAt(i);
if (ch == 'P') {
presentCount++;
} else if (ch == 'A') {
absentCount++;
}
}
System.out.println("Total Attendance - Present: " + presentCount + ", Absent: " + absentCount);
sc.close();
}
}
Comments
Post a Comment