sorting arrays with functions in C++ - c++

This is relatively basic but I'm trying to write a function that sorts an array in C++ and I don't want to do it the regular way. I made a loop to find the greatest number in array, store it as "max", save max as the current value in another array and then change the value to zero so that by the time the loop runs the next time, the previous max number will no longer be the maximum, letting the next highest take its place but for some reason, this doesn't work. what did I do wrong?
#include <iostream>
using namespace std;
void mysort(int arr[10]){
int max = 0;
int high[10];
int count;
for (int j=0; j<10; ++j){
for(int i=0; i<10; ++i){
if (arr[i]> max){
max= arr[i];
count=i;
}
}
cout<<"the "<< count+1<<" largest is: "<< max<<"\n";
high[j]= max;
*arr[count]= 0;
}
}
main(){
int pass[10] = {1,2,3,4,5,6,7,8,9,0};
mysort(pass);
}

Your max never gets reset, so on first iteration it gets set to 9 and stays that for the rest of the execution
#include <iostream>
using namespace std;
void mysort(int arr[10]){
// int max = 0; **this was the problem**
int high[10];
int count;
for (int j=0; j<10; ++j){
int max = 0;
for(int i=0; i<10; ++i)
{
if (arr[i]> max)
{
max= arr[i];
count=i;
}
}
cout<<"the "<< count+1<<" largest is: "<< max<<"\n";
high[j]= max;
arr[count]= 0;
}
}
int main(){**you should also add return type to int main**
int pass[10] = {1,2,3,4,5,6,7,8,9,0};
mysort(pass);
}

Your inner loop always set max to 9 on its final iteration, and your outer loop only ever reads max once the inner loop is completed, so high[j] will always be 9.

Related

I want to store input in array. and print the array elements but cout line isn't working

I am new in programming,
basically in this program, it takes input from user and storing in array, 5 elements. After loop ends it should give the elements back but it seems that the last line is not working.
include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[size];
}
cout<<guess[size];
return 0;
}
guess[size] is out of bounds. The last valid index in an array with size elements is size-1. Further, string guess[size]; is not valid C++ when size is not a constant expression. At the very least it should be const int size = 5;. You wrote a loop to take input and you also need a loop to print all elements.
This is the correct loop to read the input:
const int size=5;
std::string guess[size];
for (int i=0; i < size; i++){
std::cin >> guess[i];
}
You can modify it so that both input and output should use i as the loop subscript.
//cover #
#include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[i];
}
for (int i = 0; i < size; ++i) {
cout<<guess[i];
}
return 0;
}
Use Range based Loops when You want to Print whole array, so you won't get an "Out-Of-Bounds" error. Because the Index in array are Zero Based Always remember the last index is (length_of_array - 1)
using namespace std;
int main()
{
int size = 5;
string guess[size];
for (int i=0; i<size;i++)
{
cin >> guess[i];
}
// range based loop
for (int i : guess)
{
cout << i << endl;
}
return 0;
}

Given and unsorted array arr , of size n of non-negative integers, find a continuous subarray which adds to number sum. Help in getting output

#include <iostream>
using namespace std;
int main()
{
int n;
n=4;
int arr[n]={1,2,3,8};
int sum;
sum=5;
int curr=0;
cin>>sum;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
curr+=arr[j];
if(curr==sum){
cout<<i;
}
cout<<curr<<endl;
}
}
}
For the given question I need to find the starting and ending index of such a subarray. I have tried the above code but am not able to get the right output. Please guide me.
I think your code only needs some minor modifications. You should add
some code to handle the case where your running sum is greater than the target sum, and you should also re-initialize your running sum correctly.
There may be some efficient solution that is faster than O(n^2), which I am not aware of yet. If someone knows of a solution with a better time complexity, please share with us.
Below is a simple algorithm that has the time complexity of O(n^2). (It may not have the most efficient time complexity for this problem).
This function prints out the 2 indices of the array. The sum of all elements between these 2 indices inclusively will equal the target sum.
void Print_Index_of_2_Elements(int array[], int total_element, int target)
{
// Use Brute force . Time complexity = O(n^2)
for (int i = 0; i < total_element; i++)
{
int running_sum = array[i];
// Second for loop
for (int j = (i + 1) ; j < total_element; j++)
{
if (running_sum == target)
{
cout << "Two indices are: " << i << " and " << j;
return; // Found Answer. Exit.
}
else if ( running_sum > target )
break;
else // running_sum < target
running_sum += array[j];
}
}
cout << " Sorry - no answer was found for the target sum.";
}
If you are someone that is a beginner in subarrays or arrays for the case. Then this code is for you:
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int sum;
cin>>sum;
int curr=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(curr==sum){
cout<<i+1<<" "<<j;
return 0;
}
else if (curr>sum){
curr=0;
}
else if(curr<sum){
curr+=arr[j];
}
}
}
return 0;
}
If you have any doubts regarding this, feel free to comment and let me know.

Finding the Lowest sum in a 2d array by picking 1 element from each row

I am writing a code where 2d matrix array is given and by choosing 1 element from each row you must output the smallest sums. Sums as in you must give n number of minimum sums
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n;
cin>>n;
int hist[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>hist[i][j];
}
}
int num=pow(n,n);
int sum[num];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
sum[i]=sum[i]+hist[i][j];
}
}
for(int i=0;i<n;i++){
cout<<sum[i]<<" ";
}
return 0;
}
example input would be:
3
1 8 5
9 2 5
10 7 6
The output will be
9 10 12
since 1+2+6=9; 1+2+7=10; 1+2+10
The main problem I am facing would be that I can't find the lowest sum or even the sums I tried to brute force it put it won't work.
Could you help me fix the code so that at least I could find the sums?
Many problems with your code (it's not even legal C++). But the problem that is causing your current question is that you must initialise sum to zero. at the moment you have garbage values in sum.
int sum[num] = {0};
Some other issues
int num=pow(n,n);
This calculates n to the power of n, but there are only n squared sums. So this would be better
int sum[n*n] = {0};
But the big issue, the issue that makes your code illegal C++, is that in C++ array dimensions must be compile time constants not variables. So this
int hist[n][n];
and this
int sum[num];
are not legal C++. They are legal in C, which is why your compiler is accepting them, but not every C++ compiler would. Since you are trying to write C++ code you should use a vector. Here's your code rewritten to use vectors.
#include <vector>
using std::vector;
...
vector<vector<int>> hist(n, vector<int>(n));
...
vector<int> sum(num, 0);
...
That's it nothing else needs to change.
Instead of brute forcing, why not realize that the smallest path is simply the smallest element of each row and the second smallest path is the smallest element of the first n-1 rows, and the second smallest element of n.
You can elegantly express this by sorting the rows of the matrix first and then keeping a counter of where you are at each row:
#include <algorithm>
#include <iostream>
#include <vector>
struct path {
path(int n) : n(n), indexes(n) {}
// Add one to last row index, then carry over to previous rows.
path& operator ++() {
indexes.back()++;
for (int i = n-1; i >= 0; i--) {
if (indexes[i] == n) {
indexes[i] = 0;
indexes[i-1]++;
} else {
break;
}
}
return this;
}
int n;
std::vector<int> indexes;
};
Now your problem is as simple as:
int main() {
int n;
cin>>n;
std::vector<std::vector<int>> hist(n, std::vector<int>(n));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>hist[i][j];
}
// sort each row after reading
std::sort(hist[i].begin(), hist[i].end());
}
int num_minimum_sums = n;
path p(n);
while (num_minimum_sums-- > 0) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += hist[i][p.indexes[i]];
}
std::cout << sum << std::endl;
++p;
}
}

Sorting by selection in an array c++

so my program should be able to take several numbers from the user until the last number is "999". Then, it should be able to print out an array having all the numbers entered sorted. I have to use sorting by selection (by comparing values in each index).
I tried by best and i don't seem to know what is going wrong
this is my code: (sorry for the lack of tidiness and comments, I'm in a hurry)
#include <iostream>
using namespace std;
int main() {
int n;
int i;
int sentinel =999;
int A[250];
cout <<"Please enter the list of nbs ending with 999"<< endl;
cin>>n;
i=0;
int nblist;
while(n!=sentinel)
{
A[i]=n;
cin>>n;
i++;
}
nblist = i-1;
int minindex;
i =0;
int min;
int k;
k=0;
min=A[k];
for(k=0;k<nblist;k++)
{cout<<k<<endl; int i =0;
while(i<nblist){
cout<<i<<endl;
if (A[i]< min)
{
min= A[i];
if (A[i]==min)
{minindex=j;}
i++;
//cout<< "the array containing min is "<< minindex << endl;
}
cout<<"The nb of array is "<<i<<"its filled with"<< A[i]<<endl;
}int temp;
temp= A[k];
A[k]=A[minindex];
A[minindex]=temp;
//cout<<"The nb of array is "<<k<<"its filled with"<< A[k]<<endl;
//cout<<"The nb of array is "<<minindex<<"its filled with"<< A[minindex]<<endl;
int counter=0;
while(counter<nblist)
{ cout<<"The nb of array is "<<counter<<"its filled with"<< A[counter]<<endl;
counter++;
}
}
return 0;
}

Function returning sum of even numbers in an array

So the prompt I was given was "Write a function that is given an array of ints and returns the sum of the even numbers in the array. The function is not given the length of array, but the last number in the array is -1. For example, if the array contains {2,3,5,4,-1} the function returns 6. Use the header int sumEven(int myArray[]). "
and the code I've written so far is
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; i++;){
if (myArray[i] >=0) {
sum+=myArray[i];
}
}
return sum;
}
But it keeps returning back zero's? I'm not seeing what I'm doing wrong here
The typical order of parameters to a for() loop are like so:
for(<initialize variable>; <end condition>; <increment variable>)
In your example, you have the i++ as your second parameter to the for loop, which is incorrect. It will return 0 (since i starts as 0, and i++ is post-increment, so it returns 0 and then increments to 1) and your for loop will exit immediately, since 0 evaluates to false.
Instead, replace the end condition with the end condition you've described: myArray[i] != -1. You should also include a check to see if the number is even before adding it to sum, which can be done by checking to see if the remainder when divided by 2 is 0.
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; myArray[i] != -1; i++){
if(myArray[i] % 2 == 0)
sum += myArray[i];
}
return sum;
}
The error is in the for loop. You should change the for loop to for (int i=0; ; i++) and you should also add a break statement to exit the for loop.
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; ; i++){
if (myArray[i] >=0) {
sum+=myArray[i];
}
else
{
break;
}
}
return sum;
}
int sumEven(int arr[]) {
int sum = 0;
// int len = (sizeof(arr)/sizeof(*arr)); // Since this will not work for all cases.
// auto len = end(arr) - begin(arr);
for (int i = 0; arr[i] >= 0; i++) {
if(arr[i]%2==0)
sum += arr[i];
}
return sum;
}
i guess the
for (int i=0; i++;){
make no iterations, cause condition to continue loop is "i++" - which is initialy zero.
Replace it with following for example
for (int i=0; i < array_length; i++;){