# Lesson 4: Strings, if and for statements

### 8 Responses

1. Alvin & Johnatan says:

Challenge 2

#include
#include
int main (int argc, const char * argv[])
{
int sum1 = 0;
int sum2 = 1;
int totalSum = 0;

for (int i = 0 ; i < 9 ; i++) {
std::cout << totalSum << std::endl;
totalSum = sum1 + sum2;
sum1 = sum2;
sum2 = totalSum;

return 0;
}

• Stanley Sim says:

Almost. But the start shows 0,1,2,3,… which is not correct. It should be 0,1,1,2,3,…
How to rectify this bug?

• Alvin & Johnatan says:

#include
#include
int main (int argc, const char * argv[])
{
int zero = 0;
int sum1 = 0;
int sum2 = 1;
int sum3 = 0;
int totalSum = 0;

for (int i = 0 ; i < 2 ; i++)
{
std::cout << totalSum << std::endl;

totalSum = sum1 + sum2;
sum1 = sum2;
sum1 = sum3;
sum3 = totalSum;
}

for (int i = 0 ; i < 8 ; i++)
{
std::cout << totalSum << std::endl;

totalSum = sum1 + sum2;
sum1 = sum2;
sum2 = totalSum;
}
return 0;
}

• Stanley Sim says:

Good try, but give yourself some more time to write a more elegant code. At least this works.

• Alvin & Johnatan says:

int main(int argc, const char * argv[])

{
int A = 0;
int B = 1;
int C = 0;

for (int i = 0 ; i < 10 ; i++)
{
if ( C = '1' )
{
std::cout << A << std::endl;
}

else
{
std::cout << C << std::endl;
}

C = A + B;
A = B;
B = C;
}

return 0;
}

• Stanley Sim says:

Program doesn’t run. Syntax error. Did you try it?

Try this:

int x = 0, y = 1, z = 0;

std::cout << x << std::endl; std::cout << y << std::endl; for (int i = 0; i < 8; i++) { z = x + y; std::cout << z << std::endl; x = y; y = z; }

• Alvin & Johnatan says:

Correction:

}
return 0;
}

2. Alvin says:

Tried it, sir. It worked and yours too.