This is a Java code for printing the armstrong number from a user input a minimum digit to a user input maximum digit.
I'm getting no errors. The problem is that I the program prints an output of value 1.
How can I fix this?
package armstrong;
import java.util.Scanner;
public class armstrong {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
System.out.println("enter min number");
int min=obj.nextInt();
System.out.println("enter max number");
int max=obj.nextInt();
int a;
for (int j = min; j <=max; j++)
{
int temp = j ;
int l=digit(j);
System.out.println(l);
int sum=0;
if(j>0)
{
a=j%10;
sum=(int) (sum+Math.pow(a,l));
j=j/10;
}
if(sum == temp)
System.out.println(temp);
//else
//System.out.println(n+ " is not an armstrong number");
}
}
//java.lang.Math.pow(double a, double b)
public static int digit(int x){
int z=0;
if(x<0)
{
x=x * -1;
}
else if(x==0)
{
x=1;
}
while(x>0)
{
x=x/10;
z++;
}
return z;
}
}
This is because you are altering your for loop index variable, j, inside the loop. The j = j/10 line automatically makes j go back to 0, and it can never increase when inside the loop, making your for loop stuck.
You should be altering the temp variable you created instead
this should work to not have your for loop be infinite:
for (int j = min; j <=max; j++)
{
int temp = j ;
int l=digit(j);
System.out.println(l);
int sum=0;
if(j>0)
{
a=temp%10;
sum=(int) (sum+Math.pow(a,l));
temp=temp/10;
}
if(sum == j)
System.out.println(j);
//else
//System.out.println(n+ " is not an armstrong number");
}
You still have a lot of work to do on your algorithm, however.
Take a look at this: http://www.programmingsimplified.com/java/source-code/java-program-armstrong-number
Related
Lets assume i have a 2x3 matrix where row denote student and column denote marks.
eg:[[67,80,56],
[32,26,31]]
need to find the average of each row and assign a grade based on avg. if avg>40 then return "p" else return "F".
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=2;
int m=5;
int mark[][]=new int[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
mark[i][j]=sc.nextInt();
}
}
String result=grade(mark);
System.out.println("RESULT:"+result);
}
public static String grade(int mark[][])
{
int n=2,m=5,avg=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int sum=0;
sum=sum+ mark[i][j];
if(j==m)
{
avg=sum/m;
}
}
if(avg>=90)
{
return "A+";
}
else if(avg<40)
{
return "F";
}
}
return null;
}
}
IN the above code my my average value is initialised to 0.scope of average in for loop is not reflected in outside loop.how to correct itenter image description here
You are declaring the sum variable inside your 2nd loop it should be declared before your 2nd loop starts. If you declare it inside it will not have the calculated value from the previous iteration.
Also you can easily calculate avg outside the loop and then gor for your cheking.
EG:
int n=2;
int m=3;
int[][] mark = { { 67,80,56 }, { 32,26,31} };
// grade function
for (int i = 0; i < n; i++) {
int sum=0;
for (int j = 0; j < m ; j++) {
sum=sum+ mark[i][j];
}
int avg = sum / m;
System.out.println(avg);
//your code to check pass/fail
}
Also Don't return if you want to print values for each row. Instead of return use print there.
if(avg>=90)
{
System.out.println("GRADE")
}
First of all, if you need to print the grade of every student separately you will need to call your grade method for every student's marks. So put your method call in a for loop.
for(int i = 0; i < n; i++) {
System.out.println(grade(mark[i]))
}
Consequently, the definition of your method changes to
public static String grade(int mark[]) {
...
}
And at last, your if(j==m) check will always be false, cause in your code, j will never reach m in your for loop. It comes to a simple calculation of array element's sum.
public static String grade(int mark[][])
{
int m = 5, avg = 0;
int sum = 0;
for(int j = 0;j < m; j++) {
sum = sum + mark[i][j];
}
avg = sum / m;
if(avg >= 90)
{
return "A+";
}
else if(avg < 40)
{
return "F";
}
}
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1
{
public static void main()
{
int num, sum=0;
int i;
for(num=1; num<100; num++)
{
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
Change your code to :
public static void main(String[] s1) throws Exception {
int num, sum = 0;
int i;
for (num = 1; num < 100; num++) {
for (int j = 1; j <= num - 1; j++) { // change made here
if (num % j == 0) {
sum = sum + j;
}
}
if (sum == num) {
System.out.println(sum);
}
sum = 0; // change made here
}
}
Key takeaways:
Reset sum to 0 once done with inner iteration
In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself
1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.
2) you need to iterate while j <= num/2;!
3) consider using Java 8, I'll write some sample here for you.
See my example here, this is so beautiful:
public class PerfectNumbersDemo {
public static void main(String[] args) {
IntStream.range(1, 100)
.filter(PerfectNumbersDemo::isPerfect)
.forEach(System.out::println);
}
private static boolean isPerfect(int number) {
return number == IntStream.rangeClosed(1, number / 2)
.filter(i -> number % i == 0)
.sum();
}
}
This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.
However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.
You need to:
sum = 0 with every loop iteration
iterate until < num and not <= num
Here's the fixed code:
public static void main(String[] args) {
int sum;
for(int num = 1; num < 100; num++) {
sum = 0;
for(int j = 1; j< num; j++) {
if(num % j == 0) {
sum += j;
}
}
if(sum == num) {
System.out.println(sum);
}
}
}
Output:
6
28
So, your code have some minor problems and I will try to pinpoint them out.
1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.
You code will look like this.
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1 {
public static void main()
{
int num;
for(num=1; num<100; num++)
{
int sum = 0;
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
public class factors{
public static void main(String args[]){
int sum=0;
for(int k=2;k<=30;k++){
for(int i=1;i<k;i++)
{
if(k%i==0)
sum=sum+i;
}
if(k==sum)
System.out.println(sum);
sum=0; //sum=0 is very important.
}
}
}
OUTPUT
6
28
class PERFECT
{
public static void main(String args[])
{
int i,j,S,
for(i=1;i<=100;i++)
{
S=0
for(j=1;j<i;j++)
{
if(i%j==0)
S+=j;
if (S==i)
System.out.println(i+"is perfect");
}
}
}
}
Here is an alternate way of finding perfect numbers.
if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
As these numbers get real big real fast, using BigInteger is recommended.
This computes the first 10 perfect numbers.
int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
BigInteger val = BigInteger.valueOf(i);
if (val.isProbablePrime(99)) {
BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
if (!mersenne1.isProbablePrime(99)) {
continue;
}
BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
System.out.printf("%3d: %,d\n",count, mersenne1.multiply(mersenne2));
if (count++ >= N) {
break;
}
}
}
prints
1: 6
2: 28
3: 496
4: 8,128
5: 33,550,336
6: 8,589,869,056
7: 137,438,691,328
8: 2,305,843,008,139,952,128
9: 2,658,455,991,569,831,744,654,692,615,953,842,176
10: 191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216
I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}
First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}
I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.