I need help with this assignment

I need to write a code that loads 5 numbers from a user and sums up the ones that have only 2 digits. I tried with if statements directly but couldnt get it to work. This is my newest attpemt with booleans. This code succesfully determines which numbers are 2 digit by giving true(1) or f alse (0) response. I just dont know how to continue.

int main() {
bool bra;
bool brb;
bool brc;
bool brd;
bool bre;
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
if (a < 100 && a>9) {
bra = true;
}
else {
bra = false;
}
if (b < 100 && b>9) {
brb = true;
}
else {
brb = false;
}
if (c < 100 && c>9) {
brc = true;
}
else {
brc = false;
}
if (d < 100 && d>9) {
brd = true;
}
else {
brd = false;
}
if (e < 100 && e>9) {
bre = true;
}
else {
bre = false;
}
}
Last edited on
welcome! Next time use code tags, the <> on the editor or html style with [] around code and /code

you have a nice attempt. But this is a new coder thing ... to repeat code by hand with tons of excess variables and complicated logic.

to fix it, you can put
int result{};
then in each if statement, where you set the bools, instead say
result += that value. Now, you no longer need bools or elses at all!

putting that together, we get this monster:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main() 
{
int a, b, c, d, e;
int result{};
cin >> a >> b >> c >> d >> e;
if (a < 100 && a>9) {
result += a;
}
if (b < 100 && b>9) {
result += b;
}
if (c < 100 && c>9) {
result += c;
}
if (d < 100 && d>9) {
result += d;
}
if (e < 100 && e>9) {
result += e;
}
}


but, there are better ways. Do you know loops? If not, soon you will find ways to do this neater. Boolean expressions eval to 1 (true) or zero (false) and you can exploit that numerically. So, with a loop and that idea, consider this either as a preview or another way to think about it.. see how you only need 1 variable now, and the repeated code is only shown once?
1
2
3
4
5
6
7
8
9
10
11
int main()
{
    int result();
    int n;
    for(int i = 0; i < 5; i++)
      {
          cin >> n;
          result += (n>=10 && n < 100)*n; //same as if just shorter
      }
}
Last edited on
Maybe a bit easier to understand for a beginner.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
  int sum = 0;
  int n;
  for(int i = 0; i < 5; i++)
  {
    cin >> n;
    if(n >= 10 && n <=99)
      sum += n;
  }
}
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

constexpr int NoNums {5};

int main() {
	int result {};

	for (int i {}, n {}; i < NoNums && (std::cin >> n); result += (n >= 10 && n < 100) * n, ++i);

	std::cout << result << '\n';
}

Topic archived. No new replies allowed.