Subscribe to Invariance_Under_Translation        RSS Feed
-----

Pointers &Arrays revised

Icon Leave Comment
Here is an improvement upon that last snippet of code. When programming, we want to try and modularize our code as much as possible. We can do this with functions, which in turn will make our code easier to read and troubleshoot. I took the bubble sort out of the main function and created it's own seperate sub-function, enjoy.

#include<iostream>
 
using namespace std;
 
void arraySort(int array3[], int length);
 
int main() {
 
int array1[] = {5, 15, 25, 35, 45};
 
int array2[] = {10, 20, 30, 40, 50};
 
int * pointer1;
int * pointer2;
 
int temp, temp1, temp2, temp3;
 
cout<<"Here are your current arrays: "<<endl;
for(int i = 0; i < 5; i++) {
cout<<array1[i]<<", ";
}
cout<<endl;
for(int j = 0;j < 5;j++) {
cout<<array2[j]<<", ";
}
 
temp = array1[3];
 
temp1 = array1[4];
 
temp2 = array2[0];
 
temp3 = array2[1];
 
pointer1 = &array1[3]; *pointer1 = temp2;
pointer2 = &array1[4]; *pointer2 = temp3;
 
pointer1 = &array2[0]; *pointer1 = temp;
pointer2 = &array2[1]; *pointer2 = temp1;
 
arraySort(array1, 5);
arraySort(array2, 5);
 
cout<<endl;
cout<<endl;
 
cout<<"Here are your sorted arrays: "<<endl;
 
for(int i = 0; i < 5; i++) {
cout<<array1[i]<<", ";
}
cout<<endl;
for(int j = 0;j < 5;j++) {
cout<<array2[j]<<", ";
}
 
cin.get();
 
}
 
void arraySort(int array3[], int length) {
for(int m = 0; m < length; m++)  {
  for (int n = 0; n < m; n++) {
 
	 if (array3[n] > array3[n+1]) {
 
	int tempVar = array3[n+1];
 
	array3[n + 1] = array3[n];
 
	array3[n] = tempVar;
 
   }
  }
 }
}

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

January 2018

S M T W T F S
 123456
78910111213
14151617181920
212223 24 252627
28293031   

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)