How to get rid "+" word in loop
Jan 26, 2021 at 7:17am UTC
How to get rid "+" on output
example:
i input: 6, the output is: 1 + 2 + 3 + 4 + 5 + 6 + = 21
but i want + after six is deleted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Input = " ;
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
cout << i << " + " ;
}
cout << " = " << sum;
return 0;
}
Last edited on Jan 26, 2021 at 7:18am UTC
Jan 26, 2021 at 7:49am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13
int n, sum = 0;
cout << "Input = " ;
cin >> n;
for (int i = 1; i < n+1; ++i) {
sum += i;
if (i != n) {
cout << i << " + " ;
}
else { cout << i; }
}
cout << " = " << sum;
return 0;
Last edited on Jan 26, 2021 at 7:50am UTC
Jan 26, 2021 at 7:57am UTC
This is another way (print the last number in the end, outside the loop):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
int main()
{
int n ;
std::cin >> n ;
int sum = n ;
for ( int i = 1 ; i < n ; ++i )
{
sum += i ;
std::cout << i << " + " ;
}
std::cout << n << " == " << sum << '\n'
<< n << " * " << n+1 << " / 2 == " << n * (n+1) / 2 << '\n' ;
}
Jan 26, 2021 at 9:14am UTC
1 2 3 4 5 6 7 8 9 10
#include <iostream>
using namespace std;
int main()
{
int n, i = 1;
cout << "Input n: " ; cin >> n;
for ( cout << i; i < n; cout << " + " << (++i) );
cout << " = " << ( n * n + n ) / 2;
}
Jan 26, 2021 at 9:15am UTC
thank you everyone i appreciate it
Jan 26, 2021 at 10:57am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
using namespace std;
int main()
{
int n {}, sum {1};
cout << "Input = " ;
cin >> n;
cout << 1;
for (int i = 2; i <= n; sum += i++)
cout << " + " << i;
cout << " = " << sum;
return 0;
}
Topic archived. No new replies allowed.