Repository navigation
Expand file tree
/
Copy pathwhile_loop
More file actions
358 lines (306 loc) · 12.7 KB
/
Copy pathwhile_loop
File metadata and controls
358 lines (306 loc) · 12.7 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import java.util.Scanner;
public class while_loop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// TODO: SECTION 1 - Basic While Loops
// Example 1: Simple counting with while loop
System.out.println("--- Counting from 1 to 5 ---");
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++;
}
// Example 2: Reverse counting
System.out.println("\n--- Counting down from 10 to 1 ---");
int countdown = 10;
while (countdown >= 1) {
System.out.print(countdown + " ");
countdown--;
}
System.out.println();
// Example 3: Even numbers using while loop
System.out.println("\n--- Even numbers from 2 to 20 ---");
int even = 2;
while (even <= 20) {
System.out.print(even + " ");
even += 2;
}
System.out.println();
// TODO: SECTION 2 - While Loops with Conditionals
// Example 1: Sum of numbers (skip multiples of 5)
System.out.println("--- Sum of numbers from 1 to 100 (skip multiples of 5) ---");
int sum = 0;
int k = 1;
while (k <= 100) {
if (k % 5 != 0) {
sum += k;
}
k++;
}
System.out.println("Sum: " + sum);
// Example 2: Count odd and even numbers
System.out.print("\nEnter a range limit: ");
int rangeLimit = scanner.nextInt();
int oddCount = 0, evenCount = 0;
int counter = 1;
while (counter <= rangeLimit) {
if (counter % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
counter++;
}
System.out.println("Odd numbers: " + oddCount);
System.out.println("Even numbers: " + evenCount);
// TODO: SECTION 3 - Mathematical Operations with While Loops
// Example 1: Prime number checker
System.out.print("Enter a number to check if it's prime: ");
int num = scanner.nextInt();
boolean isPrime = true;
int m = 2;
if (num <= 1) {
isPrime = false;
} else {
while (m <= num / 2) {
if (num % m == 0) {
isPrime = false;
break;
}
m++;
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
// Example 2: Factorial calculation
System.out.print("\nEnter a number to calculate factorial: ");
int n = scanner.nextInt();
long factorial = 1;
int f = 1;
while (f <= n) {
factorial *= f;
f++;
}
System.out.println("Factorial of " + n + ": " + factorial);
// Example 3: Number reversal
System.out.print("\nEnter a number to reverse: ");
int numToReverse = scanner.nextInt();
int originalNum = numToReverse;
int reversedNum = 0;
while (numToReverse != 0) {
int digit = numToReverse % 10;
reversedNum = reversedNum * 10 + digit;
numToReverse /= 10;
}
System.out.println("Original number: " + originalNum);
System.out.println("Reversed number: " + reversedNum);
// Example 4: Digital root calculation
System.out.print("\nEnter a number to find its digital root: ");
int digitalNum = scanner.nextInt();
while (digitalNum >= 10) {
int digitSum = 0;
while (digitalNum > 0) {
digitSum += digitalNum % 10;
digitalNum /= 10;
}
digitalNum = digitSum;
System.out.println("Sum of digits: " + digitSum);
}
System.out.println("Digital root: " + digitalNum);
// TODO: SECTION 4 - Do-While Loops
// Example 1: Menu system using do-while
int choice;
do {
System.out.println("\n--- Simple Calculator Menu ---");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
choice = scanner.nextInt();
if (choice >= 1 && choice <= 4) {
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.println("Result: " + (num1 * num2));
break;
case 4:
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error: Division by zero!");
}
break;
}
} else if (choice == 5) {
System.out.println("Thank you for using the calculator!");
} else {
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 5);
// Example 2: Robust input validation
int validInput = -1;
int attempts = 0;
int maxAttempts = 3;
while (validInput < 1 || validInput > 100) {
if (attempts >= maxAttempts) {
System.out.println("Maximum attempts reached. Using default value: 50");
validInput = 50;
break;
}
System.out.print("Enter a number between 1 and 100 (attempt " + (attempts + 1) + "/" + maxAttempts + "): ");
validInput = scanner.nextInt();
if (validInput < 1 || validInput > 100) {
System.out.println("Invalid input! Number must be between 1 and 100.");
attempts++;
}
}
System.out.println("Valid input received: " + validInput);
// TODO: SECTION 6 - Practical Applications
// Example 1: Bank Account System
System.out.println("--- Simple Bank Account System ---");
double balance = 1000.00; // Starting balance
int transactionChoice;
do {
System.out.println("\nCurrent Balance: $" + balance);
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
transactionChoice = scanner.nextInt();
switch (transactionChoice) {
case 1: // Deposit
System.out.print("Enter deposit amount: $");
double depositAmount = scanner.nextDouble();
if (depositAmount > 0) {
balance += depositAmount;
System.out.println("Deposit successful! New balance: $" + balance);
} else {
System.out.println("Invalid deposit amount!");
}
break;
case 2: // Withdraw
System.out.print("Enter withdrawal amount: $");
double withdrawAmount = scanner.nextDouble();
if (withdrawAmount > 0 && withdrawAmount <= balance) {
balance -= withdrawAmount;
System.out.println("Withdrawal successful! New balance: $" + balance);
} else if (withdrawAmount > balance) {
System.out.println("Insufficient funds! Current balance: $" + balance);
} else {
System.out.println("Invalid withdrawal amount!");
}
break;
case 3: // Check Balance
System.out.println("Current balance: $" + balance);
break;
case 4: // Exit
System.out.println("Thank you for using our banking system!");
break;
default:
System.out.println("Invalid option! Please try again.");
}
} while (transactionChoice != 4);
// TODO: SECTION 7 - Break and Continue Statements
System.out.println("\n=== SECTION 7: Break and Continue Statements ===\n");
// Example 1: ATM withdrawal with limits
System.out.println("--- ATM Withdrawal System ---");
double dailyLimit = 500.00;
double totalWithdrawn = 0;
int withdrawalAttempt = 1;
while (true) {
System.out.println("\nAttempt #" + withdrawalAttempt);
System.out.println("Daily limit: $" + dailyLimit);
System.out.println("Already withdrawn: $" + totalWithdrawn);
System.out.println("Remaining limit: $" + (dailyLimit - totalWithdrawn));
System.out.print("Enter withdrawal amount (0 to exit): $");
double amount = scanner.nextDouble();
if (amount == 0) {
System.out.println("Thank you for using our ATM!");
break; // Exit the loop
}
if (amount < 0) {
System.out.println("Invalid amount! Please enter a positive value.");
continue; // Skip to next iteration
}
if (totalWithdrawn + amount > dailyLimit) {
System.out.println("Error: Exceeds daily withdrawal limit!");
continue; // Skip to next iteration
}
totalWithdrawn += amount;
System.out.println("Withdrawal of $" + amount + " successful!");
if (totalWithdrawn >= dailyLimit) {
System.out.println("Daily limit reached! No more withdrawals allowed today.");
break; // Exit the loop
}
withdrawalAttempt++;
}
// Example 2: Work day reminder system
System.out.println("\n--- Work Schedule Reminder ---");
int day = 1; // 1 = Monday, 7 = Sunday
while (day <= 7) {
if (day == 6 || day == 7) { // Weekend
String dayName = (day == 6) ? "Saturday" : "Sunday";
System.out.println("Day " + day + " (" + dayName + "): Weekend - No reminders");
day++;
continue; // Skip to next iteration
}
// Determine day name
String workDayName;
switch (day) {
case 1: workDayName = "Monday"; break;
case 2: workDayName = "Tuesday"; break;
case 3: workDayName = "Wednesday"; break;
case 4: workDayName = "Thursday"; break;
case 5: workDayName = "Friday"; break;
default: workDayName = "Unknown"; break;
}
System.out.println("Day " + day + " (" + workDayName + "): Sending work reminder!");
day++;
}
System.out.println("Work schedule completed for the week.");
// Example 3: Prime number finder with break
System.out.println("\n--- Prime Number Finder ---");
System.out.print("Enter a range to find primes (e.g., 100 for 1-100): ");
int primeRange = scanner.nextInt();
System.out.println("Prime numbers from 1 to " + primeRange + ":");
int currentNum = 2;
int primeCount = 0;
while (currentNum <= primeRange) {
boolean isPrimeNum = true;
int divisor = 2;
// Check if currentNum is prime
while (divisor <= currentNum / 2) {
if (currentNum % divisor == 0) {
isPrimeNum = false;
break; // No need to check further
}
divisor++;
}
if (isPrimeNum) {
System.out.print(currentNum + " ");
primeCount++;
// Add line break every 10 primes for readability
if (primeCount % 10 == 0) {
System.out.println();
}
}
currentNum++;
}
System.out.println("\nTotal prime numbers found: " + primeCount);
}
}