+ 1

If arrays start from 0, why do we start from 1 in a for loop?

Hello, I was just wondering why we start an array from 0 but when we use it in a for loop we start from 1. Shouldnt it be x < 4;? #include <iostream> using namespace std; int main(){ int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; } cout << sum << endl; return 0; } Also, why is the return needed?

2nd Jan 2017, 1:11 AM
Kamran Tayyab
Kamran Tayyab - avatar
3 Antworten
+ 5
Here is the flow of the program: 1.) x = 0, adds the element at index 0, which is the 1st element (11), to 'sum' 2.) x = 1, adds the 2nd element (35) to 'sum' 3) x = 2, adds the 3rd element (62) to 'sum' 4) x = 3, adds the 4th element (555) to 'sum' 5) x = 4, adds the 5th element (989) to 'sum' 6) x = 5, loop does not continue because 5 is NOT less than 5 (5 < 5 = false) if you were to do < 4 as the condition, then the program would run but it would not get that fourth element, because when x = 4, the condition would turn false (4 < 4 = false) and thus it would terminate before going through the whole array. What I think you meant is perhaps using the condition "x <= 4" which means when x is less than OR equal to four. That would also work and produce the same result as x < 5. For your second question, returning 0 is used for a debugger (be it a human debugger or a debugger program) to know that, if the program reaches that return statement and returned a 0, then it ran successfully. 0 is the usual number used for "success". If the program crashes prior to that, then the debugger will never receive that 0 (program flow never reaches it), and thus knows that it was unsuccessful. Since your main method is declared as "int main()", the "int" makes it mandatory to return something. You can also write the main method as "void main()", meaning you don't have to return something.
2nd Jan 2017, 1:30 AM
Ramel Mammo
Ramel Mammo - avatar
0
Thanks @Ramel. That clarified it alot.
2nd Jan 2017, 1:42 AM
Kamran Tayyab
Kamran Tayyab - avatar
0
@Kamran Welcome!
2nd Jan 2017, 6:48 PM
Ramel Mammo
Ramel Mammo - avatar