C++ program cant find mistake [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
this program creates random number array where elements wit arguments 1,3,5,7...,19 are negative and this program should find biggest negative element but when l test program it writes some random number (6784345 instead of array element) can you help me find mistake ?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
int main()
{
int a[20],nn,i;
srand(time(0));
for(i=0;i<20;i++)
{
if(i%2==0) a[i]=rand()%(61);
else
a[i]=(rand()%(61))*(-1);
}
printf("Formirani niz je:\n");
for(int i=0;i<20;i++)
{
printf("\ "); printf("%d",a[i]);
}
najneg(a,&nn);
printf("\n\nNajveci negativni clan niza je:%d\n",nn);
return 0;
}

In this code, …
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
you forgot to dereference the pointers,
void najneg(int *pa,int *nn)
{
*nn=0;
for(int i=0;i<20;i++)
{
if(*(pa+i)<*nn) *nn=*(pa+i);
}
}
The most important fix for this function is to change its name to something readable and self-descriptive, with no arbitrary shortenings. When choosing names, think about making the calling code readable and clear. So E.g., najneg → most_negative_value_in.
Secondly, instead of logical out-argument, use the function return value.
Third, if the function doesn't need to change data, use const to let it offer a guarantee that it won't change the data.
Fourth, avoid magic numbers like 20: pass the array size as argument.
This, plus some purely cosmetic changes, yields:
int most_negative_number_in(int const* const a, int const size)
{
int n=0;
for(int i=0; i<size; ++i)
{
if(a[i]<n) { n = a[i] };
}
return n;
}

This function should be
void najneg(int *pa,int *nn)
{
*nn=0; //As you want to modify nn.
for(int i=0;i<20;i++)
{
if(pa[i]<*nn) *nn=pa[i]; //Here, you want to compare values and swap them. Not just address.
}
}
Do not try to complicate it.

In addition to what others have pointed out:
You can simplify the content of your for loops:
for(i = 0; i < 20; i++)
{
// The array slot is assigned a random value
// whether the index is positive or negative.
a[i] = rand() % 61;
// If the index is odd, change the value
// to a negative number.
if(i % 2 == 1)
{
a[i] *= -1;
}
}
In the next loop, you should combine into one printf call:
for(int i = 0; i < 20; i++)
{
printf("\ %d", a[i]);
}
Also, what is "\ " in the format specifier, a tab or a space?

Related

Is this the correct implementation of Insertion Sort? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
OUTPUT
#include <iostream>
using namespace std;
int main()
{
//declaring the size of array and taking input from the user
int n = 0;
cout<<"Enter the Number of elements you want in the Array : ";
cin>>n;
//checking the user input
if(n <= 0)
{
cout<<"Not Possible\n";
return 1;
}
//declaring array of size 'n' and taking input from user
int list[n];
cout<<"Enter the Elements of the array of size "<<n<<" : ";
for(int i = 0; i < n; i++)
cin>>list[i];
//Insertion Sort
int swap = 0; //number of swaps
int comp = 0; //number of comparison
int temp; //temporary variable
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(list[j] < list[j-1])
{
//swapping equivalent to shifting
temp = list[j-1];
list[j-1] = list[j];
list[j] = temp;
comp++;
swap++;
}
else
{
comp++;
break;
}
}
//printing the iteration
cout<<"Iteration "<<(i+1)<<" : ";
for(int k = 0; k < n; k++)
cout<<list[k]<<" ";
cout<<"\n";
}
cout<<"\nSwap : "<<swap<<"\n";
cout<<"Comparison : "<<comp<<"\n";
cout<<"Sorted Array : ";
for (int i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
return 0;
}
Is this implementation of insertion sort correct because I have seen many implementation online using while loop and other things?
If not can you point out what is wrong?
Thanks in advance
link - https://github.com/ish-u/DiscreteStructures/blob/master/InsertionSort.cpp
No, this is a different type of sort, known as bubble sort. It still sorts, but insertion sort works in a different way, by keeping the array sorted at all times (moving elements if a new insertion would break the ordering).
So instead of just tagging new elements to the end of the array where you read them from cin, you should place each element directly in the right spot in the array. This will likely involve moving existing elements in order to keep the array sorted.
Note that your line
int list [n];
is wrong; you cannot allocate memory this way (and I'm surprised it even compiles). A better choice would be to use std::vector.

How can I clear the variable after while loop is done [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a program that multiplies matrices. And here I have got two variables "i" and "q" which at the beginning are both 0. While the loops proceed variables ("i" and "q") change their values. However after the loops are done I need "i" and "q" to come back to the value 0, so the loops can repeat themselves for different "w" and "k" . How can I do so??
int wynik[x][z]; //table that holds the result of the multiplication
int i=0;
int q=0;
int wyn=0;
for(int w=0; w<x; w++)
{
for(int k=0; k<z; k++)
{
while((i<y) && (q<v) )
{
wyn = (tab1[w][i] * tab2[q][k]) + wyn;
i++;
q++;
}
wynik[w][k] = wyn;
}
}
set those to 0 after the outer loop is done:
int wynik[x][z]; //table that holds the result of the multiplication
int i=0;
int q=0;
int wyn=0;
for(int w=0; w<x; w++)
{
for(int k=0; k<z; k++)
{
while((i<y) && (q<v) )
{
wyn = (tab1[w][i] * tab2[q][k]) + wyn;
i++;
q++;
}
wynik[w][k] = wyn;
}
//HERE
i = 0;
q = 0;
}
I feel like the most natural way according to your current design would be to change the most inner while loop into for (int i = 0, q = 0; (i < y) && (q < v); i++, q++). This lets for loop manage modification of i and q and both are inside the scope of the inner for loop since they are not needed anywhere else.
I would rethink the design. It sounds like a great example to study some algorithms.
Just dropping this here ;)
https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm

why is bubble sort not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...

passing values in C++ - treat 1: exc bad access [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have problems with following code:
void mc_duurtijd(int multiproject)
{
double random_getal[MULTIPROJECT][PROJECTEN][ACTIVITEITEN][RUNS];
double stochastische_duurtijd_berekenen[MULTIPROJECT][SCENARIO][PROJECTEN][ACTIVITEITEN][RUNS];
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
for (int r = 0; r < RUNS; r++)
{
random_getal[multiproject][p][i][r]=dis(gen);
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
for (int r=0;r<RUNS;r++)
{
stochastische_duurtijd_berekenen[multiproject][s][p][i][r]=bepaal_stochatische_duurtijd(random_getal[multiproject][p][i][r],multiproject,s, p, i, r);
}
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{ stochastische_duurtijd[multiproject][s][p][i]=0.0;
for (int r=0;r<RUNS;r++)
{
stochastische_duurtijd[multiproject][s][p][i]+=stochastische_duurtijd_berekenen[multiproject][s][p][i][r];
}
stochastische_duurtijd[multiproject][s][p][i]=stochastische_duurtijd[multiproject][s][p][i]/RUNS;
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
stochastische_duurtijd[multiproject][s][p][i]=floor(stochastische_duurtijd[multiproject][s][p][i]/scale+0.5)*scale;
}
}
}
void berekeningen_initieel(int multiproject)
{
mc_duurtijd(multiproject);
bereken_CP_per_project_stochastisch(multiproject);
bereken_CP_max_stochastisch(multiproject);
for (int s=0;s<SCENARIO;s++)
{
bereken_backward_stochastisch(multiproject, s);
}
for (int s=0;s<SCENARIO;s++)
{
bereken_slack_stochastisch(multiproject);
}
toekennen_activiteitID(multiproject);
}
int main()
{
mp =0;
scale=0.000000000001;
srand(time(NULL)); // the random seed is initialized to a value representing the current time (calling time) to generate a different value every time the program is run.
inlezen_data();
print_output();
for (int multi =0; multi<MULTIPROJECT;multi++)
{
berekeningen_initieel(multi);
maak_planning(multi);
bereken_doelfunctie(multi);
print_evaluatie(multi);
}
return 0;
}
The problem starts when I try to run berekeningen_initieel(multi); So for the first iteration multi =0. I am passing this value into the function berekeningen_initieel(int multiproject). Here multiproject = 0 which is normal. But then I want to call the function mc_duurtijd (int multiproject). So I do this by doing mc_duurtijd(multiproject). Here the value of multiproject is equal to 0. but when I debug my code the function mc_duurtijd(int multiproject), here multiproject is NOT equal to zero but to 18455399351 (this all the time changes when I try to run my program). I really don't understand why the value 0 is not passing to the mc_duurtijd(int multiproject) function. Can someone help me?
Almost all C execution environments use a stack to store local variables and return addresses from nested function calls. The size of the stack is usually configurable; typically it is capped at 1 MiB or so.
Given MULTIPROJECTEN = 420; PROJECTEN=3; ACTIVITEITEN=32; RUNS=100 random_getal in mc_duurtijd is approximately 32 MiB in size. Attempting to execute the program results in a stack overflow.
Use dynamic memory allocation (i.e. malloc) for large buffers.
As pointed by #Nick, I also confirmed that this is most probably because of your array is too big for a function. But there is a workaround for this. You can move the array declaraation to outside function like this:
#define MULTIPROJECTEN 420
#define SCENARIO 4
#define PROJECTEN 3
#define ACTIVITEITEN 32
#define RUNS 100
double random_getal[MULTIPROJECT][PROJECTEN][ACTIVITEITEN][RUNS];
double stochastische_duurtijd_berekenen[MULTIPROJECT][SCENARIO][PROJECTEN][ACTIVITEITEN][RUNS];
void mc_duurtijd(int multiproject) { ... }
void berekeningen_initieel(int multiproject) { ... }
int main() { ... }

How do i implement bubblesort and where [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The task is to implement a bubblesort function followed by a linearsearch aka "linsok" in my "familj" array. the array keeps both the name and the age, so i want to sort the array after their age and print it out. ive got the line search to work but now im stuck with the bubblesort.
The problem is that i dont know how to make my bubble sort code work for this code.
so do i implement the second piece of code in this?
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string namn;
int alder;
void skrivUt(string _namn, int _alder)
{
namn = _namn;
alder = _alder;
}
};
int linsok(Person* PersonArray, int key)
{
for (int i = 0; i < 4; i++)
{
if (PersonArray[i].alder == key)
return i;
}
return -1;
}
int main()
{
Person familj[4];
familj[1].skrivUt("Emma",23);
familj[3].skrivUt("Emilia",29);
familj[2].skrivUt("Johan",26);
familj[0].skrivUt("Timmy ",21);
int index = linsok(familj,22); //the age of the person im looking for.
if(index== -1)
cout << "Personen hittades ej!"; //person not found
else
//prints out the persons name and the index.
cout << "Personen heter " << familj[index].namn << " hen finns på index " << index << endl;
cin.get();
return 0;
}
This is the piece of bubble-sort code i used before and it works.
int p [] = {10,56,73,23,31,24,43};
int a = 6;
for (int i = 0; i < a; i++)
{
int nrLeft = a - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j] > p[j+1])
{
int temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
for(int i = 0; i < 7; i++)
cout << p[i] << endl;
cin.get();
It's likely that you want to convert this to a function that you pass your array of Person objects to, along with the size of it, and then you just access the part that you want to compare. Since you'd be implementing it as a function, you can use it in the same way you use your linsok function, although you'd probably want it to return the sorted array as opposed to an index.
Disclaimer for following code: Neither run nor compiled
Person* bubbleSort(Person* p, int size)
{
for (int i = 0; i < size; i++)
{
int nrLeft = size - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j].alder > p[j+1].alder)
{
Person temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
return p;
}
That's based off you sorting them by alder (which I guess is age? I don't speak Swedish(?)) You just need to provide the signature, and alter it based on your needs, but the basic idea is that you just change what you compare, and the data types.
Another way to do this is to return an int or void(But you should return an int to tell you if it was successful or not), and pass a pointer to the array, so Person** in the signature, and operate directly on that array, but that's a little more difficult, and arguably bad practice, depending on use case.