public class NestedCountLoop
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 1; sum < 5050; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
So I have a little homework assignment for my intro programming class to use a nested loop to accept positive integer input and add all of the integers within the interval from 1 to that input. My mind is playing games with me and I'm having trouble getting going. I know I need a scanner and whatnot, and it has to print every result from 1 to n such as "The sum of 1 to 100 is 5050." Any advice is helpful
Information on scanner at from http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner sc = new Scanner(System.in);
for (int i = o; i < 100; i++){
int upperLimit = sc.nextInt();
for (int w = 0; w < upperLimit; w++){
sum = sum + i;
}
System.out.println("Sum is " + sum);
}
public class NestedCountLoop
{
public static void main(String[] args)
{
int to = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; sum < to; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
How about this one? It takes an input from the command line (arg0), and adds every number to your number (not inclusive).
So you have to compile your java file with javac, then you can run:
javac NestedCountLoop.java
java NestedCountLoop.class 100
On the other hand, the a previous solution mentioned the javadoc for your scanner, if you really need to use it. :)
System.out.println("Enter your maximum number: ");
// get the input
Scanner input = new Scanner(System.in);
int max = input.nextInt();
int sum = 0;
// iterate through an array to sum up the numbers
for (int i = 1; i < max; i++) {
sum = sum + i; // sum += i;
}
// print out the sum after you counted everything
System.out.println(sum);
import java.util.Scanner;
public class sumoftenIntegerInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
for(int i=1; i<=10; i++){
System.out.println("Enter integer input " + i + ":");
int a = input.nextInt();
sum = sum + a ;
}
System.out.println("Total is:" + sum );
}
}
Related
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'm working on this book by Randall S. Fairman, 3D Astronomy with Java, having limited experience with Java myself. He uses this LineReader class instead of Scanner or anything to take user input. The exercise I'm stuck on asks you to use LineReader to get values for an array and find the average of the values in the array. This is what I came up with, doing my best, and it doesn't work. When I try to run it, it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Average.main(Average.java:10)
Code:
import ui.LineReader;
public class Average {
public static void main(String[] args) {
int average;
int sum = 0;
for (int j = 0; j < 5; j++) {
int i = LineReader.queryInt("Give me a number: ");
int [] M = new int [i];
sum = sum + M[i];
}
average = sum/5;
System.out.println("The average of those numbers is " +average);
}
}
You don't need the int[]M = new int[i]; line.
Just do sum += i;
Your updated code:
import ui.LineReader;
public class Average {
public static void main(String[] args) {
int average;
int sum = 0;
for (int j = 0; j < 5; j++) {
int i = LineReader.queryInt("Give me a number: ");
sum += i;
}
average = sum/5;
System.out.println("The average of those numbers is " +average);
}
}
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.
I am trying to create an array with 'total' amount of numbers between min and max. And then, sort them using bubble sort. When i execute, i get all zeros. Could someone find what is going wrong? A prompt reply would be appreciated.
import java.util.*;
import java.util.Random;
public class final_project
{
public static void main(String[] args)
{
int numbers[];
int i, min, max, total;
int num;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a minimum random value");
min = scan.nextInt();
System.out.println("Please enter a maximum random value");
max = scan.nextInt();
System.out.println("Please enter the amount of random numbers");
total = scan.nextInt();
numbers = new int[total];
i = 0;
total = 0;
while ( i < total )
{
num = min + (int)(Math.random()*max);;
numbers[i] = num;
total += num;
i += 1; /* i = i + 1; */
}
bubbleSort(numbers, numbers.length);
System.out.println("Your Sorted Array Is: ");
for(i=0; i<numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
}
private static void bubbleSort(int[] numbers, int length)
{
int temp, counter, index;
for(counter=0; counter<length-1; counter++)
{
for(index=0; index<length-1-counter; index++)
{
if(numbers[index] > numbers[index+1])
{
temp = numbers[index];
numbers[index] = numbers[index+1];
numbers[index+1] = temp;
}
}
}
}
}
Change
while ( i < total )
to
while ( i < numbers.length )
Your loop doesn't execute:
i = 0;
total = 0;
while ( i < total )
...
Also you don't want to increment total. Replace your loop with:
for(int i = 0; i < numbers.length; ++i)
{
numbers[i] = num;
}
You should consider using a for loop instead of a while loop. A for loop is perfect for iterating through an array.