I have calculated the sum of a for loop range, however i do not know how to count and do the average for my solution. It must be done without any ifs. Just the For loop:
//defining the variables
// Constants & Variables here
int i;
int numStart;
int numEnd;
double sum = 0;
double average=0;
double loopCount=0;
System.out.print("Enter Start number: "); // keep print line open
numStart = console.nextInt();
System.out.print("Enter End number: ");
numEnd = console.nextInt();
//enter thevalue
for (i = numStart; i <= numEnd; i++ )
{
sum = sum + i;
loopCount = numEnd - numStart;
average = sum+1 / i;
}
System.out.println();
System.out.println( "Sum is: " + sum);
System.out.println();
System.out.println( "Average is: " + average);
System.out.println();
Why even use a for
-loop. Thanks to Gauss we know the sum of all elements in range [1 , n]
is n * (n + 1) / 2
. The number of integers in the range is simply numEnd - numStart + 1
and the average is the sum of all integers in range divided by the number of integers in the range.
So an optimized solution would look like this:
...
//got numStart and numEnd
int sum = numEnd * (numEnd + 1) / 2 - (numStart - 1) * numStart / 2;
int count = numEnd - numStart + 1;
average = sum / count;
for (i = numStart; i <= numEnd; i++ )
{
sum = sum + i;
loopcount++;
}
average = sum / loopcount;
You can do :
for (i = numStart; i <= numEnd; i++ )
{
sum = sum + i;
loopCount = numEnd - numStart;
average = sum /(loopCount+1);
}
or
for (i = numStart; i <= numEnd; i++ )
{
sum = sum + i;
loopcount++;
}
average = sum / loopcount;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.