For Loop & Array Issue.
-
I am in the process of learning how to use arrays. To be more specifc, how to modify the code of "for loops" to learn different ways to work with arrays. Listed below is a basic program where I am attempting to learn how to modify a two dimensional array. I would like to place a 1 in the first dimension and a 2 in the second dimension. The issue I do not understand is why my for loop is advancing to array element 2. Shouldn't the elements updated through the loop be [0] and [1]? Shouldn't my for loop stop when it encounters the for statement test condition <=1? What is happening is that the statement advances to element [2]. Do I have a correct understanding of the for loop? Advice is much appreciated.
#include <iostream>
using std::endl;
using std::cout;
using std::cin;int initialize[2][2]; //Initialize rows / columns
int row;
int col;int main()
{
// Two rows
for(row=0;row<=1;row++) //Populate rows last.
{
//initialize[row][col] = 2;
// Two columns
for(col=0;col<=1;col++) //Populate columns first.
{
//cout << initialize[i][col] << "1";
initialize[row][col] = 1;
cout << "Row ""Col "<< row << col << initialize[row][col] << '\n';} } }
-
I am in the process of learning how to use arrays. To be more specifc, how to modify the code of "for loops" to learn different ways to work with arrays. Listed below is a basic program where I am attempting to learn how to modify a two dimensional array. I would like to place a 1 in the first dimension and a 2 in the second dimension. The issue I do not understand is why my for loop is advancing to array element 2. Shouldn't the elements updated through the loop be [0] and [1]? Shouldn't my for loop stop when it encounters the for statement test condition <=1? What is happening is that the statement advances to element [2]. Do I have a correct understanding of the for loop? Advice is much appreciated.
#include <iostream>
using std::endl;
using std::cout;
using std::cin;int initialize[2][2]; //Initialize rows / columns
int row;
int col;int main()
{
// Two rows
for(row=0;row<=1;row++) //Populate rows last.
{
//initialize[row][col] = 2;
// Two columns
for(col=0;col<=1;col++) //Populate columns first.
{
//cout << initialize[i][col] << "1";
initialize[row][col] = 1;
cout << "Row ""Col "<< row << col << initialize[row][col] << '\n';} } }
A loop such as
for(row=0;row<=1;row++)
should be read like this: 'Set row to 0, and then keep adding 1 to row until row is no longer less or equal to 1.' So what happens is this: First iteration (row is now 0): Is row <= 1? Yes; execute the code in the loop's body and when that's done, add 1 to row. Second iteration (row is now 1): Is row <= 1? Yes; execute the code in the loop's body and when that's done, add 1 to row. Third iteration (row is now 2): Is row <= 1? No; execute the code after the loop. So although row is equal to 2 áfter the loop, row is always less or equal to 1 within the loop.