cpp pass by reference - c++

i wrote a simple sorting code on pass by reference. here i am passing an array to function and then performing the sorting operation. after passing the array i am printing the entire array as entered by user then performing the sorting operation(in descending order) but after sorting when i print the sorted array i get an output that the array index '0' contains the value '41'. if i enter the numbers less than '41' then the sorted array is displayed as '41',and then the other numbers in sorted manner. Please explain why i am getting such an output.
#include<iostream>
using namespace std;
int sort_array(int *p);
int main() {
int arr[10];
for (int i=0; i<10; i++) {
cout << "enter " << (i+1) << " value:";
cin >> arr[i];
cout << "\n";
}
sort_array(arr);
return 0;
}
int sort_array(int *p) {
int c=0;
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << "arr:"<<p[0];
cout<<"\n";
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (p[j] < p[j+1]) {
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
cout << "\n";
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << p[0];
}

It appears that you are trying to do a bubble sort on your array in sort_array(), but the logic is wrong. Try using this code instead:
int sort_array(int *p) {
int c=0;
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout << "arr:" << p[0];
cout << "\n";
for (int i=0; i < 10; i++) {
for (int j=1; j < (10-i); j++) {
if (p[j-1] > p[j]) {
c = p[j-1];
p[j-1] = p[j];
p[j] = c;
}
}
}
cout << "\n";
for (int i=0; i<10; i++) {
cout << p[i];
cout << "\n";
}
cout<<p[0];
}

The problem is in your sorting. j is from 0 to 9, and than you access p[j+1] when j = 9, p[10] is outside your array boundaries.
So fix your following part to proper sorting.
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(p[j]<p[j+1])
{
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
}
Clarification: the code above is the problematic part of the original code posted. This is NOT the fixed sorting. That is the part to be fixed.

for(int i=0;i<10;i++)
{
for(int j=0;j<9;j++)
{
if(p[j]<p[j+1])
{
c=p[j];
p[j]=p[j+1];
p[j+1]=c;
}
}
}
the sorting works fine once i changed the limit of inner loop. the problem was accessing the array index [10] but i had it declared till index [9].

Related

Fill a symmetric matrix in c++

having a trouble with a condition which tells if an element of a multidimensional array
as example arr[row][col] is exactly arr[col][row] then automatically assign the value of arr[col][row] to the same value of arr[row][col] without letting user enter it manually
That should be an example of the output
example[4][4] =
{
// 0 1 2 3
{ 0, 10, 15, 18}, // 0
{ 10, 0, 20, 14}, // 1
{ 15, 20, 0, 90}, // 2
{ 18, 14,90, 0}, // 3
here's my code
` int size;
int arr[size][size];
cout<<"Choose size of your multidimensional array [matrix]: ",cin>>size;
cout<<"Now enter your data [Respectively] \n";
for(int d=0 ; d<size ; d++)
{
for(int j=0; j<size; j++)
{
if (d==j)
{
arr[d][j]=0 ;
}
else if(arr[d][j]!=0 ) //there should be the problem
{
arr[j][d]=arr[d][j];
}
else
{
cin>>arr[d][j]; // Filling matrix
}
}
} `
Here is a Minimum Working Example (MWE) that should solve your issues:
#include <iostream>
using namespace std;
int main()
{
cout << "Choose size of your multidimensional array [matrix]: ";
int size;
cin >> size;
int arr[size][size];
cout << "Now enter your data [Respectively] \n";
for(int d=0; d<size; d++)
{
for(int j=d+1; j<size; j++)
{
if (d==j)
{
arr[d][j] = 0;
}
else if(j<d) // here laid the problem
{
arr[d][j] = arr[j][d];
}
else
{
cin >> arr[d][j]; // Filling matrix
}
}
}
// print matrix
for(int d=0; d<size; d++) {
for(int j=0; j<size; j++)
cout << arr[d][j] << " ";
cout << '\n';
}
return 0;
}
This below is even cleaner, gets rid of the conditional inside the inner loop, thank you #ThomasSablik
#include <iostream>
using namespace std;
int main()
{
cout << "Choose size of your multidimensional array [matrix]: ";
int size;
cin >> size;
int arr[size][size];
cout << "Now enter your data [Respectively] \n";
for(int d=0 ; d<size ; d++)
{
arr[d][d]=0;
for(int j=d+1; j<size; j++)
{
cin >> arr[d][j];
arr[j][d]=arr[d][j];
}
}
// print matrix
for(int d=0; d<size; d++) {
for(int j=0; j<size; j++)
cout << arr[d][j] << " ";
cout << '\n';
}
return 0;
}

How do I implement an exception handler for strings and doubles in my bubble sort?

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int hold;
int swapNumber=0;
int compare=0;
int array[10];
for(int i=0; i<10; i++)
{
cout<<"Enter 10 numbers: "<<endl;
cin>>array[i];
}
cout<<endl;
// what user inputed
cout<<"Originally entered array by the user is: "<<endl;
for(int k=0; k<10; k++)
{
cout<<array[k];
cout<<endl;
}
cout<<endl;
//begin bubblesort method
for(int i=0; i<9; i++)
{
for(int k=0; k<9; k++)
{
compare++;
if(array[k]>array[k+1])
{
hold=array[k];
array[k]=array[k+1];
array[k+1]=hold;
swapNumber++;//adding swap count by 1
}//end of if
} //end of for j
} // end of for i
//when sorted sm to large
cout<<"Sorted Array is: "<<endl;
for(int i=0; i<10; i++)
{
cout<<array[i]<<endl;
}
//how many times numbers are swapped
cout<<"Number of times Swapped: "<<swapNumber<<endl;
//how ,many times numbers are compared
cout<<"Number of times Compared: "<<compare<<endl;
getch();
}
My assignment is to add an exception handler which states "Error! ONLY INTEGER INPUT ALLOWED ".The handler is supposed to catch doubles and strings. I've tried try and catch method but i don't know quite where to place it so that it'll work. I've also read about the catch all method, which seems like what i need to do. I've just now completed my counter methods for swap and comparisons which I do believe are working fine.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int hold, swapNumber = 0, compare = 0, array[10];
const string Error = "Error! ONLY INTEGER INPUT ALLOWED!";
cout << "Enter 10 numbers: " << endl;
try
{
for ( int i = 0; i < 10; i++ )
{
cin >> array[i];
if ( !cin ) // Error in reading input stream
{
throw Error;
}
}
}
catch ( const string& E )
{
cout << E << endl;
return 0;
}
cout << endl;
cout << "Originally entered array by the user is: " << endl;
for ( int k = 0; k < 10; k++ )
{
cout << array[k] << endl;
}
cout << endl;
for ( int i = 0; i < 9; i++ )
{
for ( int k = 0; k < 9; k++ )
{
compare++;
if ( array[k] > array[k + 1] )
{
hold = array[k];
array[k] = array[k + 1];
array[k + 1] = hold;
swapNumber++;
}
}
}
cout << "Sorted Array is: " << endl;
for ( int i = 0; i < 10; i++ )
{
cout << array[i] << endl;
}
cout << endl;
cout << "Number of times Swapped: " << swapNumber << endl;
cout << "Number of times Compared: " << compare << endl;
getch();
}

Bubblesort Driving me nuts

This is pretty straightforward question. I checked online with the bubble sort code, and it looks like i am doing the same. Here's my complete C++ code with templates. But the output is kinda weird!
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
for(int j=0; j<i-1; j++){
if(a[j+1]>a[j]){
cout<<"Yes at j="<<j<<endl;
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main(){
int a[] = {1,2,6,3,4,9,8,10};
sort<int>(a,8);
for(int i = 0; i<8; i++){
cout<<a[i]<<endl;
}
return 0;
}
Output:
But when i slightly change the logic to try to sort it on ascending order. i.e., changing to : if(a[j+1]<a[j]) , The output is fine!
Where am i doing this wrong?
Thanks in advance!
The problem with your code is that you try to bubble stuff down, but loop upward. If you want to bubble stuff down, you need to loop downward so an element that needs to go down goes down as far as it needs to. Otherwise, with every iteration of i you only know that an element may be bubbled down one space.
Similarly, if you bubble things upwards, you also need to loop upwards.
If you want to see what happens, here's your code with some output statements so you can follow what's going on:
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=0; j<i-1; j++){
if(a[j+1]>a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
for(int k = 0; k < size; k++) {
cout << "\t a[" << k << "]: " << a[k] << endl;
}
cout << endl;
}
}
cout << "\n" << endl;
}
}
int main(){
int a[] = {1,2,6,3,4,9,8,10};
cout << "initially:" << endl;
for(int k = 0; k < 8; k++) {
cout << "a[" << k << "]: " << a[k] << endl;
}
cout << "\n" << endl;
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}
If you run this, you can see that for entries with higher index, there aren't enough iterations left to bubble them down all the way to where they need to go.
Also, here's code with your bubbling-down fixed (i.e. sorting in reverse order):
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=size - 1; j>i; j--){
if(a[j-1]<a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}
int main(){
int a[] = {1,2,3,4,5,6,8,10};
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}
When using bubble sort, you need to keep in mind in which directions your "bubbles" move. You first have to pick the biggest/smallest element from all the array and move it to the end at position n-1. Then pick the next one and move it to to position n.
for (int i=size; i>1; i=i-1) { // << this is different
for (int j=0; j<i-1; j=j+1) {
if (a[j] < a[j+1]) {
std::swap(a[j], a[j+1]);
}
}
}
See here for an even better implementation.
It is a logic problem:
for(int i = 0; i < size; i++){
for(int j = 0; j < (i); j++){
if(a[i] > a[j]){
cout<<"Yes at j="<<j<<endl;
T temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
You should change the a[j+1] for a[i]
You are comparing and swapping wrong numbers, look for differences here:
template <class T>
void sort(T a[], int size){
for(int i = 0; i < size; i++){
for(int j = i+1; j < size; j++){
if(a[i] < a[j]){
cout << "Yes at j=" << j << endl;
//swap(a[j], a[j+1]);
T temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}

send dynamic array of pointer to function in c++

I trying to send array to function, but my program gets stuck
int main()
{
int n, i;
bool random;
cout << "number of elements in array:"; cin >> n;
cout << "use random values?"; cin >> random;
int* arr = new int[n]; //create int array with n size
init_array(random, n, arr); //fill array using function
for (i = 0; i <= n; i++) //display array
cout << " " << arr[i];
return 0;
}
This function should fill array with random number or input from keyboard
void init_array(bool random, int n, int* arr)
{
int i;
if (random)
{
srand(time(0)); //initialize random;
for (i = 0; i < n; i++)
arr[i] = rand() % 100;
}
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
}
Is there any way send dynamic array to function?
When you do not use brackets after your for-loop, only the first statement is used as a loop:
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
This loop will attempt to print "arr[#]" n times, and then ask for an input (which will attempt to be placed in the item 1 after the last element in your array (UB).
What you want is this:
else
{
for (i = 0; i<n; i++)
{
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
}
You also have a problem with your output:
for (i = 0; i < n; i++) // <= would attempt to print 1 more item than exists in the array
And just for completeness, most of these issues go away when you use a container that does all of this for you:
int main()
{
int n = 0;
bool useRandom = false;
std::cout << "number of elements in array:";
std::cin >> n;
std::cout << "use random values?";
std::cin >> useRandom;
std::vector<int> arr(n);
init_array(useRandom, arr);
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
void init_array(bool useRandom, std::vector<int>& vec)
{
::srand(time(0)); //initialize random;
int n = 0;
std::transform(vec.begin(), vec.end(), vec.begin(), [&](int i)
{
if (useRandom)
{
i = rand() % 100;
}
else
{
std::cout << "arr[" << n++ << "]: ";
std::cin >> i;
}
return i;
});
}
Your code is asking for a number at the end because of last cin>>n
fix else part in init_array as:
else
for (i = 0; i<n; i++)
{ //Notice braces
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
Also fix:
for (i = 0; i < n; i++) //display array from index 0 to n-1
cout << " " << arr[i];

LU decomposition in c++

I am currently having some probs with my code to decompose an array into an upper(u) and lower(l) array.
I am using the doolittle method
My code:
#include <iostream>
using namespace std;
int main(){
double a[10][10];
double l[10][10];
double u[10][10];
double som=0;
int RANG;
cin >> RANG;
for(int i=0; i<RANG; i++){
for(int j=0; j<RANG;j++){
cin >> a[i][j];
}
}
for(int i=0; i<RANG; i++){
for(int j=0; j<RANG;j++){
u[i][j]=0;
l[i][j]=0;
}
}
for(int i=0;i<RANG;i++) {
l[i][i]=1;
for(int j=i;j<RANG;j++) {
for(int s=0;s<i-1;s++) {
som+= l[i][s]*u[s][j];
}
u[i][j]=a[i][j]-som;
}
for(int k=i+1;k<RANG;k++) {
double som=0;
for(int s=0;s<i-1;s++) {
som+=l[k][s]*u[s][i];
}
l[k][i]=(a[k][i]-som)/u[i][i];
}
}
cout << "l:" << endl;
for(int i=0; i<RANG; i++){
for(int j=0; j<RANG;j++){
cout << l[i][j] << "\t";
}
cout << endl << endl;
}
cout << "u: " << endl;
for(int i=0; i<RANG; i++){
for(int j=0; j<RANG;j++){
cout << u[i][j] << "\t";
}
cout << endl << endl;
}
return 0;
}
plz help if you can...
PS: not sure if it belongs here, might be better on the mathematics site
Have a look at http://download.intel.com/design/PentiumIII/sml/24504601.pdf it got complete solution along with source code!
You might want to check out QuantLib. http://quantlib.org/index.shtml
Here's an example of code that uses the QuantLib library to decompose a 3x3 array. It uses a Cholesky decomposition, but maybe it'll help. http://quantcorner.wordpress.com/2011/02/20/matrix-decomposition-with-quantlib/
Check your 's' iteration it should be
for(int s=0;s