asked 117k views
2 votes
Write a for loop that assigns summedvalue with the sum of all odd values from 1 to usernum. assume usernum is always greater than or equal to 1.

2 Answers

4 votes

Firstly, define a variable `usernum` and let's use 10 as an example. Then, define another variable `summedvalue` and set it as 0 initially. This variable will hold the sum of all odd numbers up to `usernum`.

Next, we start a for loop. This loop will go through each number in the range from 1 to `usernum` inclusive. That's why in the range function we provide `usernum + 1` as the second parameter.

Now, for every number `i` in this range, we check whether it is odd. A number is odd if it gives a remainder of 1 when divided by 2. In other words, we're checking if `i % 2` is not equal to 0 (`i % 2 != 0`).

If the current number `i` is indeed odd, we add it to `summedvalue` (`summedvalue += i`). Then, the loop goes to the next number and the process repeats itself until we've considered all numbers from 1 to `usernum`.

Finally, when the loop ends, the value of `summedvalue` is the sum of all odd numbers from 1 up to (and including) `usernum`. Return this `summedvalue`.

In the case of `usernum = 10`, the odd numbers between 1 to `usernum` are 1, 3, 5, 7, and 9. When you add them together, you get 25. That's why in this case, the result will be 25.

answered
User Namoscato
by
9.0k points
3 votes
// Input value is usernum.
// This code snippet sums 1 + 3 + 5 + ... + usernum
// The answer is stored in the variable summedvalue.

N = (int) (usernum+1)/2; // maximum number of integers to be summed
int *v = malloc(N*sizeof(int)); // allocate storage for array v

// Calculate the number of loop counts and assign array v..
count = 0;
k = 1;
while (1) {
if (k>usernum) { // do not extend v beyond usernum
break;
}
v(count) = k; // assign an odd integer to v, including usenum
count++;
k += 2; // k is an odd number
if k>usernum { // handle usernum as odd or even
k = usernum;
}
}
n = count; // the size of array v.

// Calculate the sum in a for loop
summedvalue = 0; // initialize summedvalue
for (i=0; i<=n; i++) {
summedvalue += v(i);
}


answered
User Pete Wilson
by
8.1k points
Welcome to Qamnty — a place to ask, share, and grow together. Join our community and get real answers from real people.