-3

in school we only learn python and I want to learn c++ on my own. I have learned basics and now I try to solve problems from my textbook in both languages.

n = int(input())
b=0
c=0
for i in range (1,n+1):
    b += i
    for j in range (1,i+1):
        c += j 
print(b,c)

This is in python and it works perfectly but when i try to transcipt it to c++ I don't get the good result:

for (i=1;i<a+1;i++)
    d = d+i;
    for (n=1;n<i+1;n++)
        c = c+n;

(I have not transcripted whole c++ code because it is much longer than python and just inpunts and outputs so I just took the nested loop) What am I doing wrong? please help

  • tell us what are you expecting it to do – Andam Jan 21 '18 at 14:11
  • 1
    You need to use {} in c++ for this since indentation means nothing. As a result only the line after the for() is part of the loop in both cases. – drescherjm Jan 21 '18 at 14:11
  • 2
    Have you tried using braces? (`{}`) – Nick is tired Jan 21 '18 at 14:11
  • @NickA Is correct. Unlike with python's indentation, scope blocks must be enclosed in `{}` braces in c++. You shouldn't try to learn c++ with help of Stack Overflow, that won't work well. Use a [good book](https://stackoverflow.com/q/388242) instead. –  Jan 21 '18 at 14:14
  • 3
    The important lesson to take from this, is that one should not learn one programming language by a simple "transcription" of another. – StoryTeller - Unslander Monica Jan 21 '18 at 14:15
  • Thank you very much it works now. So braces are a must :) – user9149607 Jan 21 '18 at 14:18
  • @user9149607 _"So braces are a must :)"_ Not for one liners, but I recommend to always use them. –  Jan 21 '18 at 14:20

2 Answers2

1

In C++ if you have a for loop it only loops the next statement and not the whole identation block after like in python. To do that you need to surround with curly braces. Like this:

for (i=1;i<a+1;i++)
{
    d = d+i;
    for (n=1;n<i+1;n++)
        c = c+n;
}

Otherwise your code is equivalent to this: (in C++ identation means nothing)

for (i=1;i<a+1;i++)
    d = d+i;
for (n=1;n<i+1;n++)
    c = c+n;
mdatsev
  • 3,054
  • 13
  • 28
0

First you need {}. In C++ { marks the start of a body and } means end of body of a statement such as the for loop. Otherwise your for loop will only iterate over the next statement in line:

int n = 10, b = 0, c = 0;
for (int i = 1; i <= n; i++){
    b += i;
    for (int j = 1; j <= i; j++){
        c += j;
    }
}
Ron
  • 14,674
  • 4
  • 34
  • 47
Andam
  • 2,087
  • 1
  • 8
  • 21