Adding consecutive integers from an input (Translated from Python to C++) -
i'd request on hw. think i'm close figuring out. our compsci class shifting learning python (introductory) c++. since 2 vaguely similar, we've been advised, since we're beginners, code problem in python (which we're familiar with) , translate c++ using basics learned. problem solve simple "add consecutive integers 1 number, given positive integer input." example be:
>>enter positive integer: 10 >>1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
the python code (this successful) i'm attempting translate c++ is:
num = int(raw_input("enter positive integer: ")) sum = 0 in range(1, num): sum += print i, "+", print num, "=", sum+num
and unsuccessful c++ code:
#include <iostream> using namespace std; int main() { int num; int sum; int i; sum = 0; cout << "please enter positive integer: " << endl; cin >> num; (i=0; 1 <= num; i++) { sum = sum + i; cout << << "+" << endl; } cout << num << "=" << sum + num << endl; return 0; }
but output infinite, non-ending addition sequence 0 infinity, going top bottom. worse did not print in straight line want it. can see, quite literally tried translate word-for-word; thought that'd foolproof. must wrong loop. since c++ doesn't have class of own "range" python does, thought middle condition statement ("1 <= num;") act range. why didn't "=" sign print out? , don't understand why won't terminate when reaches "num." think can help? thank in advance replies.
this:
for (i=0; 1 <= num; i++)
should be:
for (i=0; <= num; i++)
Comments
Post a Comment