-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

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
  • 2,886
  • 10
  • 25
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
  • 13,936
  • 3
  • 30
  • 47
Andam
  • 1,817
  • 1
  • 6
  • 19