Need fast help if possible

So I'm really lost with 1 task.

I have interval. For example from 1 to 6.

Calculate and deduce the sum of all cubes in the interval from n to m ([n; m]), and the odd-squared product. Check: when n = 1, m = 6, must be output: sum of Cubes 288 Square Sql. 225

I'm not sure if the google translator translated it right but for the odd numbers it should be :
1 * 1 * 3 * 3 * 5 * 5 = 225

And with the Cube

2 * 2 * 2 + 4 * 4 * 4 + 6 * 6 * 6 = 288

I have to use For and If inside For. I'm really lost with this.

I know I should't ask for homework tasks but I'm like totally stuck. I started learning 5 months ago and we barely finished with if. Now we just started For and using If inside of it.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
using namespace std;

int main() {
	
	int n = 1, m = 6;
	int result = 1;

	for (int i = n; i < m + 1; i++) {
		if (i % 2 == 0) {
			continue;
		}
		else {
			result *= (i * i);
		}
	}

	cout << result << endl;

	result = 0;

	for (int i = n; i < m + 1; i++) {
		if (i % 2 == 0) {
			result += (i * i * i);
		}
	}

	cout << result << endl;
	

	return 0;
}


Study and learn friend...
If using two loops, you should count up by 2s rather than having an if statement.

Here is a solution that uses one loop and an if statement:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    unsigned from=1, to=6;
    unsigned sumOfEvenCubes=0;
    unsigned productOfOddSquares=1;

    for (unsigned i=from; i<= to; ++i) {
	if (i%2) {
	    productOfOddSquares *=  i*i;
	} else {
	    sumOfEvenCubes += i*i*i;	    // even
	}
    }

    std::cout << "sum of Cubes " << sumOfEvenCubes
	      << " Square Sql. " << productOfOddSquares << '\n';
}

why use if when you can use ternary ;D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main() 
{
    int n = 1;
    int m = 6;
    bool odd = n&1;
    int prod = 1;
    int sum = 0;
    for (int i=n; i<=m; ++i)
    {
        odd ? prod *= i*i : sum += i*i*i;
        odd = !odd;
    }
    std::cout << prod << std::endl << sum << std::endl;
}
You guys are cracking me up. Stop it... Oh, what the hell...
Recursive solution...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>

using namespace std;

void stuffAndThings(int n, int m, int &result1, int &result2) {

	n % 2 ? result1 *= (n*n) : result2 += (n*n*n);
	n < m ? stuffAndThings(++n, m, result1, result2) : cout << result1 << endl << result2;

}



int main() {
	
	int n = 1, m = 6;
	int result1 = 1, result2 = 0;


	stuffAndThings(n, m, result1, result2);
	
	return 0;
}
Topic archived. No new replies allowed.