Return value in a loop - java

How can I return value in a for loop ? For example if I have a loop that give me 3 numbers: 1,2,3... How can I return the value of the last number (here it is 3)?
public class Cod {
public static void main(String[] args) {
exp();
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
int y=x/10;
System.out.println(y);
return y;
}
}
}

The easiest thing is to wait for the loop to finish, and then return the last value that it has produced.
The only valid reason why you need to wait for the loop to calculate all three results is that the calculation is dependent upon the value calculated by the prior iteration of the loop. In this case, here is how you can do it:
int res = 0;
for (int i = 0 ; i != 3 ; i++) {
res = calculateResult(i, res);
}
return res;
In case when you can calculate the value of the last iteration directly without running the previos iterations, there is no reason to run the loop at all.

If I understood what you are trying to do, here is your example modified:
public class Cod {
public static void main(String[] args) {
System.out.println(exp());
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
}
int y=x/10;
return y;
}
}
I don't understand why you do x/10 - instead you could just loop one less round.

I am not sure if you want to loop or break after a certain condition in a loop
To break you can do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x=x*10;
y=x/10;
System.out.println(y);
break;
}
}
This will break straight away so it will only loop once. The value of y is accessible at this point.
If you want the value of the counter variable then declare this outside the loop
int i = 1;
for (i = 1; i<=3;i++) {
x=x*10;
y=x/10;
...
}
System.out.println(i + "");
Then the value of i is accessible outside the loop.
EDIT: after comment
to get the value of y do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x *= 10;
y = y + (x/10);
}
System.out.println("y value after loop is "+ y);
}
or if y is not to be added to
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x *= 10;
}
int y = x/10;
System.out.println("y value after loop is "+ y);
}

Related

how to add elements in each row seperately and print output in 2D array

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";
}
}

Anyone know what I am doing wrong to execute this java code?

I am just trying to execute some Java code and print them out to the console, however, when I try to run it, it gives an error and says illegal start to expression. Does anyone know what is going on here?
package com.craneai;
public class Main {
public static void main(String[] args) {
public static void int F(int N) {
int X, Y, Z, I;
int X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <=N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
}
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int i = 3; i <=N; i++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
A few things to consider:
1st. You're declaring a void return and then a int, the function must have only 1 return type.
public static void int F(int N)
2nd. The method should be outside the main method
3rd. You declared X twice in the code, the second time you call it, you don't have to declare the type, the compiler will try to process it as a new variable with a name that is already in use.
4th. In your for method, you declared X, once again, Java is case sensitive, so X and x are different in the compiler.
5th. You've also declared I twice, you don't need to provide a temporary variable before calling the for method, since you can do it inside the for loop;
Looks like you're starting to learn Java, a few tips from who works with it since the Java 5..
Don't declare your variables with a single letter;
Don't declare your functions/methods with a single letter;
Don't declare your variables in UPPER CASE, always low case and camelCase;
Even as an example you should make your code cleaner, improve the readability for others, other people will be happier in the future if you do this (this include yourself).
First: you're declaring a method inside another method - see that the F method is inside the main method. Java does not support nested methods.
Second: you're declaring X and I twice.
Third: You wrote two return types to your method: void and int.
This will work:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Three main errors:
Nested method: F method inside main
Method F return int and void
You declared X and I twice.
Here is your class fixed:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X = 2, Y, Z;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Output is going to be this:
8
3
2

sum of all prime numbers between 100 and 200

I'm actually about to loose my mind... The code I wrote displays every kind of "sum" and "count" between the actual last result I want to display with System.out.print(...). Can someone help me please? What did I do wrong for it to display everything?
public class Prim {
public static void main(String[] args) {
int end = 11;
int count = 1;
long sum = 0;
for (int number = 10; count<=end; number++) {
if (isPrim(number)) {
sum = sum + number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i<number; i++) {
if (number % i == 0) {
}
}
return true;
}
}
A few things.
First, your isPrim can be optimised so that i only increments until sqrt(number).
Second, you need to return false if (number%i == 0) is true. Right now, it's always returning true, which is why your code is outputting all sums.
Third, you need to change istPrimeZahl to isPrim (or vice versa), as you haven't defined istPrimeZahl anywhere.
Fourth, you can change sum = sum + number to simply sum += number.
Finally, you probably want to move your System.out.print line two lines below, so that it only prints the sum after the loop has ended, not at every iteration of the loop.
(Also, you might want to change your for loop so that it starts at 100, not 10 :) )
If you want the final version, I've pasted it here:
public class Prim {
public static void main(String[] args) {
int end = 200;
int count = 0;
long sum = 0;
for (int number = 100; number<=end; number++) {
if (isPrim(number)) {
sum += number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i*i<=number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
The isPrim function is missing a 'return false' after the if statement. This means that isPrim will always return true, and consequently every number will get written to the console.
The System.out.print is also within for-loop, so it will print an updated sum each time. It's unclear if this is intentional, but if you want to only get a single result then that should also be moved two lines lower.
For sum of prime numbers between 100 to 200, try this code:
public class Primzahlen {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++)
if (isPrim(i))
sum += i;
System.out.print(sum);
}
public static boolean isPrim(int num) {
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
}

Write a function when given one integer x ; returns e with the following approximation

![enter image description here][1]The question:
Write a function with name ʻ expʼ that ,when given one integer x; returns
with the following approximation. In this function, you should use previous two functions to calculate factorial and power.
This is my code;
import java.util.Scanner;
public class ass7_q3 {
public static int power(int x, int y)
{
int result = 1;
for(int i = 1; i <= y; i++)
{
result = result * x;
}
return result;
}
public static int factorial(int n)
{
int fact = 1;
for(int i = 1; i<= n; i++)
fact = fact * i;
return fact;
}
public static int exp( int x)
{
int result;
result = (power(x,x) / factorial(x) );
return result;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sum = 0;
int x;
x = read.nextInt();
for(int i=0; i<=10; i++)
{
sum = sum + exp(x);
}
System.out.println(sum);
}
}
However, when I run this code, it always gives me the wrong answer.
What can I do?
You should start by working with doubles instead of integers. You can't expect to approximate a Real number using only integer calculations.
For example, power(x,x) / factorial(x) would always return an integer, since both methods return an int.
5/2 will return 2. You need cast it to double like ((double)5)/2 will return 2.5
You should think about range of integer ( in java 2,147,483,647)
if your input is grater than 12, integer can not handle.
Factorial method will return wrong value. because
factorial(12)=479,001,600 but
factorial(13)=6,227,020,800

logical error, not giving the wanted answer

I don't understand what I did wrong, there's no syntax error, but it's not giving out the answer I want. The algorithm is supposed to find the integer between 1 and 10000 to have the largest number of divisors, and state how many divisors it contains.
public class pract3ex11 {
public static void main (String [] args) {
int n;
int i;
int c=0;
int max=0;
int result;
int d;
for (n=2; n<10000; n++){
d=c;
c=0;
int x=n;
result = x;
for (i=1; i<x; i++){
result= result%i;
if (result==0){
c++;
}
if (c>d){
max=n;
}
}
}
System.out.println(max+" "+c);
}
When you set the max, you should also set d. Otherwise, the two get out of sync:
if (c>d){
d = c;
max=n;
}
You also need to assign 0 to d before the loop, and remove
d=c;
at the top of loop.
Possible solution :
public static void main(String[] args) {
int count;
int maxDivisors;
int number;
maxDivisors = 1;
number = 1;
for ( count = 2; count <= 10000; count ++ ) {
int x;
int divisors = 0;
for ( x = 1; x <= count; x++ ) {
if ( count % x == 0 )
divisors++;
}
if (divisors > maxDivisors) {
maxDivisors = divisors;
number = count;
}
}
System.out.println("The maximum number of divisors are " + maxDivisors);
System.out.println("Number is : " + number);
}

Categories