Click here to Skip to main content
15,886,793 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello guys ,
first i am beginner programmer and

i have one question...
can i Integrates the for loop in the following code to be """ for(int i=0,j=0;i<a,j<b;++i,++j)

instead of this ???

C++
#include

using namespace std;

int main(){
	
	int n,a,b;
	cin>>n>>a;
	int arr[a];
	for(int i=0;i<a;++i){
		cin>>arr[i];
	}
	cin>>b;
	int arr2[b];
	for(int j=0;j<b;++j){
		cin>>arr2[j];
	}   
	}
Posted
Updated 21-Sep-14 3:53am
v3
Comments
CPallini 24-Sep-14 3:30am    
There's no reason for doing that.

Not really, no - the number of iterations (the number of times your go round the loop) is controlled by a different user input - so if he enters two different numbers you would have to have the same loop go round two different numbers of times - which is just silly! :laugh:
It is possible, but it would take more code, be more awkward to read, and harder for the user to work out what he is supposed to be entering.

Leave it as two loops!
 
Share this answer
 
That should work if the two arrays are the same size, but then you wouldn't need two index variables anyway.
 
Share this answer
 
No. But if you have multiple input loops like that, you should extract them into a function. That way you don't have to write the same code twice. Also note that there is a mistake in your original code: you cannot define a array using a variable as size - you need to allocate the array dynamically. Also you should check whether the size is in fact a meaningful value:

C++
bool read_array(int*& arr, int& arr_size) {
   bool result = false;
   // get desired array size
   cin >> arr_size;
   // ensure reasonable size, assuming you don't really
   // want to enter more than 100 values manually
   if (arr_size > 0 && arr_size < 100) {
      // allocate array on the heap
      arr = new int[arr_size];
      // read array elements
      for (int index = 0; index < arr_size; ++index) {
         cin >> arr[index];
      }
      result = true;
   }
   return result;
}
int main () {
   int* arr = nullptr; // always initialize
   int a = 0; // initialization not so important here, but make it a habit!
   if (!read_array(arr, a) {
      cout << "Failed to read first array" << endl;
      a = 0; // reset to 0, just to be sure
   }
   int* arr2 = nullptr;
   int b = 0;
   if (!read_array(arr2, b) {
      cout << "Failed to read second array" << endl;
      b = 0; // reset to 0, just to be sure
   }
   return 0;
}
 
Share this answer
 
v2
Comments
Philippe Mori 23-Sep-14 20:45pm    
You code need some small fixes like arr_size variable declared twice and nullpt without final r on arr2 initialization.
Stefan_Lang 24-Sep-14 2:01am    
Thanks for the info, I'll fix it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900