Home > Blockchain >  How to only show last value of a C for loop
How to only show last value of a C for loop

Time:09-23

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 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;
}

CodePudding user response:

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;
}

CodePudding user response:

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;
}
  • Related