I dont know how to write the code of the following code

write a program to display the no which are divisible by 3 or 5 and add it
Hint: use modulo '%', if there is a remainder, don't print it.
Huh. I wonder if that program ever halts?
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>
using namespace std;

int main()
{
	int num = 0, store = 0;
	char choice;
	while (true)
	{
		cout << "\nEnter The Number : ";
		cin >> num;
		if (num % 3 == 0)
		{
			cout << num << " is divisible by 3\n";
			store += num;
		}
		if (num % 5 == 0)
		{
			cout << num << " is divisible by 5\n";
			store += num;
		}
		cout << "\nEnter Y To Continue or N to Quit : ";
		cin >> choice;
		if (choice == 'n' || choice == 'N')
			break;
	}
	cout << "\nThe Sum is " << store << endl;
	system("pause");
}

@bird1234 the program works but it fails to display the sum (the part I was unable to write)
bird1234's code does display the sum as soon as your enter 'n'.
What numbers did you enter?

However, bird1234's code has a problem. If you enter a number that is divisible by both 3 and 5 (e.g. 15), the number will be added to the sum twice.
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
#include<iostream>
using namespace std;

int main()
{   int num = 0, store = 0;
	char choice;
	bool divisible;
	
	while (true)
	{   divisible = false;
		cout << "\nEnter The Number : ";
		cin >> num;
		if (num % 3 == 0)
		{   cout << num << " is divisible by 3\n";
		    divisible = true;
		}
		if (num % 5 == 0)
		{   cout << num << " is divisible by 5\n";
		    divisible = true;			
		}
		if (divisible)
            store += num;
		cout << "\nEnter Y To Continue or N to Quit : ";
		cin >> choice;
		if (choice == 'n' || choice == 'N')
			break;
	}
	cout << "\nThe Sum is " << store << endl;
	system("pause");
}

Last edited on
@AbstractionAnon thanks a lot
the code works after one change in it
if( choice =='Y' || Choice== 'N')
Topic archived. No new replies allowed.