7 Replies - 377 Views - Last Post: 03 March 2012 - 09:57 AM Rate Topic: -----

#1 shifaza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 08-March 11

Breaking in a nested for loop.

Posted 02 March 2012 - 10:10 PM

I'm kind of confused as to how to do this. So i'd be glad if any of you can help me out by providing me some guidelines. I hope im able to explain my problem properly.
Im supposed to put values into a 2D array. The initialization looks like this: int arr[10][4]
So the output supposedly looks like this. Values are supposed to be inserted by user:
Test1  Test2  Test3  Test4
  0     0      0      0
  0     0      0      0  
  0     0      0      0
  -1


Thing is, when -1 is entered, the previous values are supposed to be saved and the loop is supposed to end, even if 10 columns arent reached. I have no clue as to how to do it. Ive tried putting break; statement in my code. I dont think im doing it right. Little help?

Here's my code:
void InitializeArray(int arr[10][4])
{
	for(int i=0; i<10; i++)
	{
		for(int j=0; j<4; j++)
		{
			cout<<"Input value ["<<i<<"]["<<j<<"] : ";
			cin>>arr[i][j];
		}
	}
}



Also, im supposed to find the average of the tests. Both horizontally and vertically. So that the output looks something like this:
        Test1   Test2   Test3   Test4   Average   Minimum
         0        0       0      0        0        0
         0        0       0      0        0        0 
         0        0       0      0        0        0
Average  0        0       0      0        
Minimum  0        0       0      0                 0


So.. im guessing somehow, the number of columns need to be stored in an int? But how do i do that?

Is This A Good Question/Topic? 0
  • +

Replies To: Breaking in a nested for loop.

#2 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1623
  • View blog
  • Posts: 5,714
  • Joined: 03-August 09

Re: Breaking in a nested for loop.

Posted 02 March 2012 - 10:39 PM

you can return an integer(the size) from your InitializeArray function. in this case, becuase your going to return after breaking the outer loop, you can actually just return the size from the inner loop rather than breaking.

something like the following would go inside your inner loop.
if(x == -1) {
   return size;
}


This post has been edited by ishkabible: 02 March 2012 - 10:40 PM

Was This Post Helpful? 0
  • +
  • -

#3 buffalobill  Icon User is offline

  • D.I.C Head

Reputation: 21
  • View blog
  • Posts: 188
  • Joined: 08-July 08

Re: Breaking in a nested for loop.

Posted 02 March 2012 - 10:53 PM

if you delete line 7 your array will be initialized as:
..........i ..j....
(Row) 0 0 1 2 3
(Row) 1 0 1 2 3
(Row) 2 0 1 2 3
.
.
.
(Row) 9 0 1 2 3
When you write int arr[10][4];//enough memory is reserved for 40 ints
//or on most machines 160 bites

This post has been edited by buffalobill: 02 March 2012 - 10:55 PM

Was This Post Helpful? 0
  • +
  • -

#4 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Breaking in a nested for loop.

Posted 02 March 2012 - 11:31 PM

Exiting from the inner loop of nested loops is an interesting problem. It is interesting because it causes a little strife in the venerable paradigm of structured programming.

Personally I generally use a flag variable:

Here I use "haveAll" as a flag to tell when I have all the data.
#include <iostream>
#include <vector> //using a vector rather than an array. You will probably need to stick with the array

using namespace std;

vector<vector<int> > initializeData();
void displayData(vector<vector<int> >& data);

int main() {
    cout << "Please enter values: " << endl;
    vector<vector<int> > data;
    data = initializeData();
    displayData(data);
    return 0;
}


vector<vector<int> > initializeData() {
	vector<vector<int> > data;
    bool haveAll = false; // a flag to tell when I have all the data entered
    int i = 0;
    for (int i = 0; !haveAll; ++i) { // for me I don't have a limit you would probably use: for(int i = 0; !haveAll && i < 10; ++i) { ... }
        vector<int> row(4,0);
        for(int j = 0; j < 4; ++j)  {
            int value;
            cout << "Input value ["<<i<<"]["<<j<<"] : ";
            cin >> value;
            if (value == -1) { // if the user indicated an end to data
                haveAll = true; // then we set our flag to true
                break; // exit the loop
            }
            row[j] = value;
        }
        if(!haveAll) { // this just keeps the last row from being added... if you were using an array you probably would not have this bit of logic
            data.push_back(row);
        }
    }
    return data;
}

void displayData(vector<vector<int> >& data) {
    for (int i = 0; i < data.size(); ++i) {
        for (int j = 0; j < data[i].size(); ++j) {
            cout << data[i][j] << "\t";
        }
        cout << endl;
    }
}




Other programmers don't like using flags and/or don't like complicated expressions using boolean operators. So they might use the return statement to exit the loop, or use (gasp) a goto!!!

There have been some creative ways to exit out of nested loops. So its an interesting question.
Was This Post Helpful? 0
  • +
  • -

#5 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1112
  • View blog
  • Posts: 4,619
  • Joined: 09-June 09

Re: Breaking in a nested for loop.

Posted 03 March 2012 - 12:10 AM

To add to the solutions posted above, you could also iterate the array with a single for loop along with some conditional logic for the indices.

example
#include <iostream>

#define R_SIZE 2
#define C_SIZE 4

void initializeArray(int arr[R_SIZE][C_SIZE]) {
	int input = 0;
	int r = 0, c = 0;
	while(r < R_SIZE) {
		std::cout<<"input["<<r<<"]["<<c<<"] = ";
		std::cin>>input;
		if(input == -1) {
			break;
		}
		arr[r][c] = input;
		if(c++ >= C_SIZE - 1) {
			c = 0;
			r++;
		}
	}
}
int main() {

	int arr[R_SIZE][C_SIZE];
	initializeArray(arr);
	
	std::cin.ignore();
	std::cin.get();
	return 0;

}


Was This Post Helpful? 2
  • +
  • -

#6 shifaza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 08-March 11

Re: Breaking in a nested for loop.

Posted 03 March 2012 - 09:20 AM

JJL, why separate r and c values? Also, what does cin.ignore() do? :/
Was This Post Helpful? 0
  • +
  • -

#7 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Breaking in a nested for loop.

Posted 03 March 2012 - 09:40 AM

r -row, c - column

the formatted extractor cin.operator<<() only takes what it needs to make the requested type:

cin << someInt;

will parse input for just and int and leave anything else in the input buffer. So Say that the user entered "123" and pressed enter. The input buffer has "123\n" in it:

cin << someInt;

will extract the int 123 and leave "\n" in the buffer. This can cause trouble later down the line (when you try to say keep the cmd window open).

cin.ignore() -- ignores the next char in the input buffer. So it eats that "\n" and leaves the buffer empty.


HOWEVER, it is really not a great solution because if the user enters "123abc\n" we will get this:

cin << someInt; //123 gets extracted as someInt, "abc\n" is left in the buffer
cin.ignore(); // "a" is ignored, and "bc\n" is left in the buffer.

So the cin.ignore() is common in beginner code, it is actually not a great pattern to follow, though as long as you realize what is going on it works well for basic programs.
Was This Post Helpful? 1
  • +
  • -

#8 shifaza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 08-March 11

Re: Breaking in a nested for loop.

Posted 03 March 2012 - 09:57 AM

:) Figured it!! Thanks alot!!! :D I guess i need to get more familiar with c++
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1