My question is the following, i'm just figuring out this language, now my question is about the "n" number.

What is the role of n<5, i know after this condition it continues the for or not.
But i can't find the precise explanation of the "n" . Thank you.

Why are n<5 and n<6 outputting the same result? And why n<4 is so small?

n<4 outputs 135
n<5 outputs 12206
n<6 outputs 12206
n<7 outputs 12207
n<8 outputs 12208

#include <stdafx.h>
#include <iostream>

using namespace std;

int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
  for ( n=0 ; n<5 ; n++ )
  {
    result += billy[n];
  }
  cout << result << endl;
  return 0;
}

Recommended Answers

All 2 Replies

For n < 4 you are getting(as you go through the loop):

result +=billy[0];   //billy[0] = 16, result = 16
result +=billy[1];  //billy[1] = 2, result = 18
result +=billy[2];   //result =  95
result +=billy[3];  //result = 135

What you are doing with the loop is accruing a sum result+=whatever; is shorthand for result = result + whatever; .
As your sums included that billy[4] element they got bigger but you ran out of values in the array (which might have caused a crash but the values in memory after the end of the array had been zeroed out). So you'd been tacking on terms = 0 after a while (any n>4) -- I can't explain why some terms (outside your array) were = 1 as it gave the value 12206 consistently for all terms with n >4 on my system.

My question is the following, i'm just figuring out this language, now my question is about the "n" number.

What is the role of n<5, i know after this condition it continues the for or not.
But i can't find the precise explanation of the "n" . Thank you.

n is called a loop counter. You start n at 0: for ( n=0 ; n<5 ; n++ )
At the end of the loop, you add 1 to n : for ( n=0 ; n<5 ; n++ )
Then the loop continues if n is still less than 5: for ( n=0 ; n<5 ; n++ )

Why are n<5 and n<6 outputting the same result? And why n<4 is so small?

Luck. Since billy is defined as 5 integer array, when you access billy[5] you are beyond the defined array and accessed memory you shouldn't. It just happens to work and the garbage value is used. Another result could be the program crashes since the memory is undefined. That's why you're lucky.

As for why n<4 is small and n<5 is big, use pencil and paper and execute the program at your desk (called desk-checking the program). The reason will become obvious.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.