0% found this document useful (0 votes)
63 views16 pages

Assignment No 1 Oop

Uploaded by

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

Assignment No 1 Oop

Uploaded by

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

Assignment no 1

Q1. Write a program that helps the user count his change. The program
should ask how many quarters the user has, then how many dimes, then how
many nickels, then how many pennies. Then the program should tell the user
how much money he has, expressed in dollars. If you have N eggs, then you
have N/12 dozen eggs, with N%12 eggs left over. (This is essentially the
definition of the / and % operators for integers.) Write a program that asks
the user how many eggs she has and then tells the user how many dozen eggs
she has and how many extra eggs are left over.
“ Counting Change”
import java.util.Scanner;

public class ChangeCounter {


public static void main(String[] args) {
// Create a scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user for the number of coins
System.out.print("How many quarters do you have? ");
int quarters = scanner.nextInt();
System.out.print("How many dimes do you have? ");
int dimes = scanner.nextInt();
System.out.print("How many nickels do you have? ");
int nickels = scanner.nextInt();
System.out.print("How many pennies do you have? ");
int pennies = scanner.nextInt();

// Calculate the total value in cents


int totalCents = (quarters * 25) + (dimes * 10) + (nickels * 5) + pennies;
// Convert total cents to dollars
double totalDollars = totalCents / 100.0;
// Output the result
System.out.printf("You have $%.2f.\n", totalDollars);
// Close the scanner
scanner.close();
}
}

“Counting Dozen Eggs”


import java.util.Scanner;

public class EggCounter {


public static void main(String[] args) {
// Create a scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user how many eggs they have
System.out.print("How many eggs do you have? ");
int eggs = scanner.nextInt();
// Calculate the number of dozens and extra eggs
int dozens = eggs / 12;
int extraEggs = eggs % 12;
// Output the result
System.out.printf("You have %d dozen eggs and %d extra eggs.\n", dozens, extraEggs);
// Close the scanner
scanner.close();
}
}
Q2.A gross of eggs is equal to 144 eggs. Extend your program so that it will tell
the user how many gross, how many dozen, and how many left over eggs she
has. For example, if the user says that she has 1342 eggs, then your program
would respond with Your number of eggs is 9 gross, 3 dozen, and 10 since 1342
is equal to 9*144 + 3*12 + 10.
import java.util.Scanner;

public class EggCounter {


public static void main(String[] args) {
// Create a scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user how many eggs they have
System.out.print("How many eggs do you have? ");
int eggs = scanner.nextInt();
// Calculate the number of gross, dozens, and extra eggs
int gross = eggs / 144; // 1 gross = 144 eggs
int remainingAfterGross = eggs % 144;
int dozens = remainingAfterGross / 12; // 1 dozen = 12 eggs
int extraEggs = remainingAfterGross % 12; // Leftover eggs
// Output the result
System.out.printf("Your number of eggs is %d gross, %d dozen, and %d extra eggs.\n",
gross, dozens, extraEggs);
// Close the scanner
scanner.close();
}
}

Q3: How many times do you have to roll a pair of dice before they come up
snake eyes? You could do the experiment by rolling the dice by hand. Write a
computer program that simulates the experiment. The program should report
the number of rolls that it makes before the dice come up snake eyes. (Note:
“Snake eyes” means that both dice show a value of 1.)
import java.util.Random;

public class SnakeEyesSimulator {


public static void main(String[] args) {
// Create a random number generator
Random rand = new Random();
// Initialize the number of rolls
int rollCount = 0;
// Initialize variables to store dice values
int die1, die2;
// Roll the dice until snake eyes are rolled (both dice showing 1)
do {
// Generate random dice values between 1 and 6
die1 = rand.nextInt(6) + 1;
die2 = rand.nextInt(6) + 1;
// Increment the roll count
rollCount++;
}
while (die1 != 1 || die2 != 1); // Continue until both dice show 1
// Output the result
System.out.println("It took " + rollCount + " rolls to get snake eyes (1, 1).");
}
}

Q4: Which integer between 1 and 10000 has the largest number of divisors,
and how many divisors does it have? Write a program to find the answers and
print out the results. It is possible that several integers in this range have the
same, maximum number of divisors. Your program only has to print out one
of them. You might need some hints about how to find a maximum value. The
basic idea is to go through all the integers, keeping track of the largest
number of divisors that you’ve seen so far. Also, keep track of the integer that
had that number of divisors.
public class LargestNumberOfDivisors {
// Function to count divisors of a number
public static int countDivisors(int n) {
int count = 0;
// Loop from 1 to the square root of n to find divisors
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
count++; // i is a divisor
if (i != n / i) {
count++; // n/i is also a divisor if i != n/i
}
}
}
return count;
}
public static void main(String[] args) {
int maxDivisors = 0;
int numberWithMaxDivisors = 0;
// Iterate through numbers from 1 to 10,000
for (int i = 1; i <= 10000; i++) {
int divisorsCount = countDivisors(i);
// If the current number has more divisors, update the result
if (divisorsCount > maxDivisors) {
maxDivisors = divisorsCount;
numberWithMaxDivisors = i;
}
}
// Output the number with the largest number of divisors
System.out.println("The number between 1 and 10000 with the most divisors is: "
+ numberWithMaxDivisors);
System.out.println("It has " + maxDivisors + " divisors.");
}
}

Q5: Suppose that a file contains information about sales figures for a company
in various cities. Each line of the file contains a city name, followed by a colon
(:) followed by the data forthat city. The data is a number of type double.
However, for some cities, no data was available. In these lines, the data is
replaced by a comment explaining why the data is missing. For example,
several lines from the file might look like:
 San Francisco: 19887.32
 Chicago: no report received
 New York: 298734.12
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SalesDataProcessor {


public static void main(String[] args) {
String fileName = "sales_data.txt"; // Replace with the actual file name
try {
// Create a BufferedReader to read the file
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
// Read each line of the file
while ((line = reader.readLine()) != null) {
// Split the line into city name and data
String[] parts = line.split(":");
if (parts.length == 2) {
String city = parts[0].trim();
String data = parts[1].trim();
// Check if the data is a valid number (sales data)
try {
double sales = Double.parseDouble(data);
// If it's a valid number, print the city and the sales data
System.out.println(city + ": " + sales);
} catch (NumberFormatException e) {
// If it's not a valid number, it's likely a comment about missing data
System.out.println(city + ": Missing Data (" + data + ")");
}
}
else {
// Handle any lines that don't follow the expected format
System.out.println("Invalid line format: " + line);
}
}
// Close the reader
reader.close();
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}

Q6: Write a program that will compute and print the total sales from all the
cities together. A store offers discounts based on the total purchase amount:
 Less than $100: No discount.
 $100 to $500: 10% discount.
 Above $500: 20% discount.
Ensure that the program also calculates and displays the final amount after
applying the discount. Note: How would you implement a nested if structure
to handle these conditions efficiently?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SalesWithDiscount {


public static void main(String[] args) {
String fileName = "sales_data.txt"; // Replace with your file name
double totalSales = 0.0; // Variable to accumulate the total sales
try {
// Create a BufferedReader to read the file
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
// Read each line of the file
while ((line = reader.readLine()) != null) {
// Split the line into city name and sales data
String[] parts = line.split(":");
if (parts.length == 2) {
String city = parts[0].trim();
String data = parts[1].trim();
// Check if the data is a valid number (sales data)
try {
double sales = Double.parseDouble(data);
totalSales += sales; // Add the sales figure to the total
} catch (NumberFormatException e) {
// Handle the case where data is a comment (missing report)
System.out.println(city + ": Missing Data (" + data + ")");
}
}
else {
// Handle invalid line formats (in case of misformatted lines)
System.out.println("Invalid line format: " + line);
}
}
// Nested if structure to apply the discount based on the total sales
double discount = 0.0;
if (totalSales < 100) {
// No discount if total sales are less than $100
discount = 0.0;
} else {
// If total sales are $100 or more, we apply a 10% or 20% discount
if (totalSales <= 500) {
// 10% discount if total sales are between $100 and $500
discount = totalSales * 0.10;
} else {
// 20% discount if total sales are above $500
discount = totalSales * 0.20;
}
}
// Calculate the final amount after applying the discount
double finalAmount = totalSales - discount;
// Output the total sales, discount, and final amount after the discount
System.out.println("Total Sales: $" + totalSales);
System.out.println("Discount: $" + discount);
System.out.println("Final Amount after Discount: $" + finalAmount);
// Close the reader
reader.close();
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}

Q7: Write a program that determines if a number is odd or even without


using the % operator. Example: Input: 4 → Output: "Even" Input: 5 →
Output: "Odd" Hint: Use bitwise operators or subtraction logic in your if
conditions. Note: How would you use an alternative approach to replace the
% operator?
import java.util.Scanner;

public class OddOrEvenWithoutModulus {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user for a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Use subtraction logic to determine if the number is odd or even
while (number > 1) {
number -= 2; // Subtract 2 from the number
}
if (number == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
// Close the scanner to prevent resource leak
scanner.close();
}
}

Q8: Write a program to generate Pascal's Triangle up to n rows. Pascal's


Triangle is constructed such that: The first and last values in each row are 1.
Each number in between is the sum of the two numbers above it.
import java.util.Scanner;

public class PascalsTriangle {


public static void main(String[] args) {
// Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
// Ask the user how many rows of Pascal's Triangle to generate
System.out.print("Enter the number of rows for Pascal's Triangle: ");
int n = scanner.nextInt();
// Generate and print Pascal's Triangle up to n rows
generatePascalsTriangle(n);
// Close the scanner
scanner.close();
}
// Method to generate Pascal's Triangle up to n rows
public static void generatePascalsTriangle(int n) {
// Create a 2D array to store the values of Pascal's Triangle
int[][] triangle = new int[n][];
// Loop through each row
for (int row = 0; row < n; row++) {
// Initialize the row with the appropriate number of elements (row + 1 elements)
triangle[row] = new int[row + 1];
// The first and last elements in each row are always 1
triangle[row][0] = 1;
triangle[row][row] = 1;
// Fill in the middle elements of the row (if any)
for (int col = 1; col < row; col++) {
triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col];
}
}
// Print the triangle
for (int row = 0; row < n; row++) {
// Print leading spaces for formatting (to center the triangle)
for (int space = 0; space < n - row - 1; space++) {
System.out.print(" ");
}
// Print the elements of the current row
for (int col = 0; col <= row; col++) {
System.out.print(triangle[row][col] + " ");
}
System.out.println(); // Move to the next line
}
}
}

Q9: Write a program that takes a character as input and determines if it is a:


 Vowel (a, e, i, o, u or A, E, I, O, U),
 Consonant,
 Not a letter.
Example:
 Input: A → Output: "Vowel"
 Input: z → Output: "Consonant"  Input: 1 → Output: "Not a letter"
Note: How can you handle both uppercase and lowercase inputs using if
statements?
import java.util.Scanner;

public class CharacterType {


public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user to input a character
System.out.print("Enter a character: ");
char inputChar = scanner.next().charAt(0); // Read the first character of the input
// Determine if the character is a vowel, consonant, or not a letter
if (Character.isLetter(inputChar)) {
// Convert the character to lowercase to handle both uppercase and lowercase
char lowerChar = Character.toLowerCase(inputChar);
// Check if the character is a vowel
if (lowerChar == 'a' || lowerChar == 'e' || lowerChar == 'i' || lowerChar == 'o' || lowerChar
== 'u') {
System.out.println("Vowel");
} else {
// Otherwise, it's a consonant
System.out.println("Consonant");
}
}
else {
// If the character is not a letter
System.out.println("Not a letter");
}
// Close the scanner
scanner.close();
}
}

Q10. Write a program that prints the first n rows of a Fibonacci Pattern. Each
row contains Fibonacci numbers starting from 0.
For example:
 Input: n = 5
 Output:
Copy code
0
11
235
8 13 21 34
55 89 144 233 377
import java.util.Scanner;

public class FibonacciPattern {


public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user to input the number of rows for the Fibonacci pattern
System.out.print("Enter the number of rows: ");
int n = scanner.nextInt();
// Generate the Fibonacci pattern
generateFibonacciPattern(n);
// Close the scanner
scanner.close();
}
// Method to generate and print the Fibonacci pattern
public static void generateFibonacciPattern(int n) {
// Variables to track the Fibonacci numbers
int first = 0, second = 1;
// Loop through each row
for (int row = 1; row <= n; row++) {
// For each row, print 'row' Fibonacci numbers
for (int col = 1; col <= row; col++) {
System.out.print(first + " ");
// Update Fibonacci numbers
int next = first + second;
first = second;
second = next;
}
System.out.println(); // Move to the next row
}
}
}

You might also like