idkeverynameistaken
idkeverynameistaken

Reputation: 23

How to show only the last value of a for loop?

I'm working on building a loop right now that only shows the end value. However, the code is showing all the integers though.

Here's my code:

#include <iostream>

using namespace std;

int sum = 0;

void findMultiples(int n){

    cout <<"Enter a positive integer:"<<endl;
    
  for(int i = 0; i <= n; i++)
    if (i % 3 == 0)
      cout << "Sum: "<<(sum =sum+i)<<endl;
  
}

int main() {

  int num;
  cin>>num;

  findMultiples(num);


  return 0;
}

Upvotes: 2

Views: 410

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595827

Your cout statements are in the wrong places. Try this instead:

#include <iostream>
using namespace std;

int findMultiples(int n){
    int sum = 0;
    for(int i = 0; i <= n; i++){
        if (i % 3 == 0)
            sum += i;
    }
    return sum;
}

int main() {

    cout << "Enter a positive integer:" << endl;

    int num;
    cin >> num;

    cout << "Sum: " << findMultiples(num) << endl;

    return 0;
}

Upvotes: 2

Syed Haseeb
Syed Haseeb

Reputation: 312

You are using for then if then showing output. The for and if scope area is one line without { }, so you are printing and summing at the same time and it is each time in the scope of if statement.

#include<iostream>

using namespace std;

int sum = 0;

void findMultiples(int n){

    cout <<"Enter a positive integer:"<<endl;
    
  for(int i = 0; i <= n; i++)
    if (i % 3 == 0)
      sum =sum+i;
  cout << "Sum: "<<sum<<endl;

  
}

int main() {

  int num;
  cin>>num;

  findMultiples(num);


  return 0;
}

Upvotes: 2

Related Questions