C++ variable initialization, substitution

Asked 2 years ago, Updated 2 years ago, 98 views

#include<iostream>
using namespace std;

int main()
{
    int i = 10, j = 0,k=0;
    for (i; i < 31; i++)
    {
        for (j; j < 6; j++)
            k = (i * j) + k;
    }
        cout << k << endl;
}

If you output the value is 150

#include<iostream>
using namespace std;

int main()
{
    int i , j, k=0;
    for (i=10; i < 31; i++)
    {
        for (j=0; j < 6; j++)
            k = (i * j) + k;
    }
        cout << k << endl;
}

If you output to , you will get a value of 6300.

The difference is whether you put a value when you first declare a variable or a value in a for statement, so I looked it up on the Internet and I think it's the difference between initialization and substitution, but I don't understand it clearly, so I'm writing it down here. I don't know much yet, so please take good care of me.

c++ c initialization

2022-09-20 11:32

1 Answers

#include<iostream>
using namespace std;

int main()
{
    int sum = 0;

    for (int i=10; i < 31; i++)
    {
        for (int j=0; j < 6; j++)
            sum = (i * j) + sum;
    }

    cout << k << endl;

    return 0;
}

It wouldn't be much different from a computer's point of view. But there's a big difference from the perspective of a programmer who looks at the code.

I understand that the former was written like that because the old C language did not support grammar. I don't understand that the result is different. I think something else is wrong.

There's a big difference in readability. If you write code like the former, I think they'll ask if you're making it up on purpose.


2022-09-20 11:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.