Need some help with my C++ program.

Hi, i am a really really really new to c++ (and programing overall) and im having trouble with this piece of code. The thing i want to create is:


Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17

It just prints every number out. Thanks in advance! :)

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
  #include <iostream>
#include <string>

using namespace std;

int main()

{

int number;
int x = 1;



cout << "Write a number" << endl;
cin >> number;

while(number >= x){
if((x/3) || (x/5)){
cout << x << endl;
x++;
}
else
{
x++;
}
}


}
Last edited on
This is wrong:
if((x/3) || (x/5))
?

You want to look at the modulus operator:
http://www.cprogramming.com/tutorial/modulus.html


You also aren't summing anything either, you're just incrementing a number. If i was you i'd ignore the multiple of 3 and 5 thing first and just get this working:
Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
Last edited on
if((x/3) || (x/5)
This seems wrong. You're just saying:
if (x divided by three OR x divided by 5)
You don't really have a condition there. You're just dividing some numbers.

Presumably you actually want something like
if (x divides by three exactly OR x divides by 5 exactly)
Last edited on
first bit:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{

	int n = 0;	
	int sum = 0;
	cout << "Write a number" << endl;
	cin >> n;

	for(int i=0;i<=n;i++)
	{
		sum+=i;
	}
	return 0;
}
Oh, right @mutexe thx i will check it out!

@Moschops yeah, thx! :D

Awesome you guys could help me out in a friendly way, aka not screaming im a total dumbass haha <3
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
#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    int sum = 0;


	cout << "Write a number" << endl;
	cin >> n;

 for(int i=0;i<=n;i++)
 {


	 if ((i % 3 == 0) || (i % 5 == 0))
     {
       sum+=i;
     }
 }
 cout << sum << endl;

}


Thanks again :D
Last edited on
Topic archived. No new replies allowed.