i've been assigned to write a program in C++ that, given an array of integers, finds the smallest (including its index) and largest number, and their subtraction. To do this, i decided to write three functions for each operation and it works perfectly. The problem is i don't know how to get the index of the smallest number.
I tried solving the problem by creating a variable and putting in inside a for loop and then print it. However, the program always says the index is 0.
Here you can see an example of how the output should be:
int myvector[200] = {40, 250, 9, 50} // Array containing 4 numbers
It should output:
The smallest number is: 9 at index 2
The largest number is: 250
Their subtraction is: 241
Here you can see my code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int find_smallest (int myvector[], int smallest, int index){
smallest = myvector[0];
index = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] < smallest) {
smallest = myvector[i];
index = i;
}
}
return smallest;
}
int find_largest (int myvector[], int largest) {
largest = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] > largest) {
largest = myvector[i];
}
}
return largest;
}
int sub_minmax (int myvector[], int subtraction, int smallest, int largest){
subtraction = largest - smallest;
return subtraction;
}
int main()
{
int myvector[200], smallest, largest, subtraction, index;
for(int i=0;i<4; i++) {
cout<<"Enter the number " <<i+1<<endl;
cin>>myvector[i];
}
smallest = find_smallest(myvector, smallest, index);
largest = find_largest(myvector, largest);
subtraction = sub_minmax(myvector, subtraction, smallest, largest);
cout<<endl;
cout<<"the smallest number is: "<<smallest<<" at index "<<index<<endl;
cout<<"the largest number is: "<<largest<<endl;
cout<<"the substraction is: "<<subtraction<<endl;
return 0;
}
Any help will be appreciated, thanks
Pass index by reference.
int find_smallest (int myvector[], int smallest, int &index)
change this
int find_smallest (int myvector[], int smallest, int index)
to
int find_smallest (int myvector[], int smallest, int &index)
here index is not local variable it reference to value passed, so any changes in index in function reflect is original value.
if you want to return both you can use struct or class.
Related
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;
}
}
I am gonna want maximum value from the array using a pointer. But I am not getting the accurate value. Please, help.
#include <iostream>
using namespace std;
int main()
{
int* largest;
int a[5]={4,5,666,7,8};
largest=a;
for(int i=1; i<5; i++)
{
if(*largest<*(largest+i))
{
*largest=*(largest+i);
largest=largest+i;
}
}
cout<<*largest;
}
I am getting 7339544 as an output rather than 666. I don't know what I am doing wrong.
You're indexing outside the array, causing undefined behaviour.
You're doing this
largest
|
v
| 4 | 5 | 666 | 7 | 8 |
^
|
largest + 1
then
largest
|
v
| 5 | 5 | 666 | 7 | 8 |
^
|
largest + 2
then
largest
|
v
| 5 | 7 | 666 | 7 | 8 | outside
^
|
largest + 3
(Note that you're also modifying the array, which you shouldn't.)
The main problem is that you're trying to use largest for three purposes simultaneously:
iterating,
storing the largest value,
storing the position of the largest value.
It should only point to the largest array element; you should only change its value, not the value of the element it points to.
int main()
{
const int a[5] = {4, 5, 666, 7, 8};
const int* largest = a;
for (int i = 1; i < 5; i++)
{
if (*largest < a[i])
{
largest = &a[i];
}
}
cout << *largest;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generateNumber(int lower_limit, int upper_limit);
void fillArr(int *arr, unsigned int arrSize, int lower_limit, int upper_limit);
void printElementsArr(int *arr, unsigned int arrSize);
int maxElementArr(int *arr, unsigned int arrSize);
int main()
{
char expression;
int l_l, u_l;
int arrSize;
do{
srand(time(0));
printf("Insert array size:\n");
scanf("%d", &arrSize);
if(arrSize < 0){
while (arrSize<0){
printf("Insert positive array size:\n");
scanf("%d", &arrSize);
}
}
int array[arrSize];
printf("Insert lower limit of an array:\n");
scanf("%d", &l_l);
printf("Insert upper limit of an array:\n");
scanf("%d", &u_l);
while(u_l<l_l){
printf("the upper limit (%d) is smaller then the lower limit (%d), set a new upper limit of an array: ",u_l,l_l);
scanf("%d",&u_l);
}
fillArr(array, arrSize, l_l, u_l);
printElementsArr(array, arrSize);
maxElementArr(array, arrSize);
getchar();
printf("If you want to end the program insert 'n' else insert any key: ");
scanf("%c",&expression);
}while(expression != 'n');
}
//---------------------------------------------------------------------------------------------------------
int generateNumber(int lower_limit, int upper_limit){
return rand() % (upper_limit-lower_limit)+lower_limit;
}
void fillArr(int *arr, unsigned int arrSize, int lower_limit, int upper_limit){
int i = 0;
for (i; i < arrSize; i++){
*(arr+i)= generateNumber(lower_limit, upper_limit);
}
}
void printElementsArr(int *arr, unsigned int arrSize){
int i = 0;
printf("\n");
for (i; i < arrSize; i++){
printf("%d.element of an array: %d\n" ,i+1, *(arr+i));
}
}
int maxElementArr(int *arr, unsigned int arrSize){
int i = 1, max= *arr;
for(i; i<arrSize; i++){
if(max < *(arr+i)){
max = *(arr+i);
}
}
printf("\nThe max element of an array is: %d\n",max);
}
Because this code consists of multiple parts I created each independent functions for each problem a then I initially called them in my main function except the one that generates numbers. I used that one in the function where it fills the array with the numbers.
I created the function for generating a random numbers, filling an array with the numbers and printing every each element(number) of an array.
The reason I created the random number generator is because it is more dynamic than static array with pre-defined numbers and size of an array.
Also before the fill and print functions are called, first I ask the user for an array size and if the array size is lower than 0 therefore it will ask the user to insert a positive number and a I also ask user for a lower and an upper limit of an array and if the upper limit is lower than the lower limit a question with the information that the upper limit is lower than the upper one will pop-up over and over again with the option to insert a new upper limit unless the user inserts a number that is higher than the lower limit.
Also, the whole program is in loop with the question in the end if they want to end the program.
#include <iostream>
using namespace std;
int main()
{
int* largest;
int a[5]={4,5,666,7,8};
largest=a;
for(int i=1; i<5; i++)
{
if(*largest < a[i])
{
largest = &a[i];// This works perfectly
//largest = largest+i; There is no meaning of this line
}
}
cout<<*largest;
}
I have an array of integers A [N]. I want to find indices n and m such that the sequential sum from the nth element to the mth is maximum. Search time is limited by the value of N.
It's my code:
#include <iostream>
#include <vector>
using namespace std;
int MaxSum(vector<int> &A){
int N=A.size();
int n=0;
int m=0;
int prev_max=A[0];
int sol_max=A[0];
for (int i=1; i<N; i++){
prev_max=max(A[i], A[i]+prev_max);
if (prev_max>=sol_max){
sol_max=prev_max;
}
}
cout<<"m="<<m<<endl;
cout<<"n="<<n<<endl;
// cout<<sol_max<<endl;
}
int main()
{
vector<int> a={{-2},{1},{-3},{4},{-1},{2},{1},{-5},{4}};//for example: n=3; m=6
MaxSum(a);
}
I tried to insert these counters and each time the program didn't work correctly, and it is clear why. But, unfortunately, I don't know how to put them correctly (I hope you can fix it
This type of problem can be solved using Kadane's Algorithm and the complexity is linear.
The primary idea of this problem is to look for positive contiguous segments of the array. And finding the maximum sum among all positive contiguous segment. And also ignore segment that has negative sum (as we are intended to find the maximum sum).
Note: This idea will fail if all the values are negative. To fix this issues you can check if all the elements are negative or not and find the maximum value.
int MaxSum(vector<int>&A) {
int n=0,m=0;
int max_so_far=0,max_ending_here=0;
int prevIndex = 0;
for(int i=0;i<A.size();i++) {
max_ending_here += A[i];
if(max_ending_here > max_so_far) {
max_so_far = max_ending_here;
n = prevIndex;
m = i;
}
if(max_ending_here < 0) {
max_ending_here = 0;
prevIndex=i+1;
prevIndex=i+1;
}
}
cout<<"n: "<<n<<endl;
cout<<"m: "<<m<<endl;
}
The Sieve of Eratosthenes and Goldbach's Conjecture
Implement the Sieve of Eratosthenes and use it to find all prime
numbers less than or equal to one million. Use the result to
prove Goldbach's Conjecture for all even integers between four and
one million, inclusive.
Implement a function with the following declaration:
void sieve(int array[], int num);
This function takes an integer array as its argument. The array
should be initialized to the values 1 through 1000000. The
function modifies the array so that only the prime numbers remain;
all other values are zeroed out.
This function must be written to accept an integer array of any
size. You must should output for all primes numbers between 1 and
1000000, but when I test your function it may be on an array of a
different size.
Implement a function with the following declaration:
void goldbach(int array[], int num);
This function takes the same argument as the previous function
and displays each even integer between 4 and 1000000 with two
prime numbers that add to it.
The goal here is to provide an efficient implementation. This
means no multiplication, division, or modulus when determining if
a number is prime. It also means that the second function must find
two primes efficiently.
Output for your program: All prime numbers between 1 and 1000000
and all even numbers between 4 and 1000000 and the two prime
numbers that sum up to it.
DO NOT provide output or a session record for this project!
This is the code that I have so far, my problem is that it displays numbers higher than 1,000 as 1s, how can I go about this, thank you!
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
void sieve(int array[], int num);
void goldbach(int array[], int num);
const int arraySize = 1000000;
int nums[arraySize];
int main(){
for (int i = 0; i <= arraySize; ++i)
nums[i] = 1;
nums[0] = nums[1] = 0;
sieve(nums, arraySize);
for(int i = 0; i < 10000; ++i){
if (nums[i] > 0){
cout << nums[i] << " ";
}
}
goldbach(nums, arraySize);
return 0;
}
void sieve(int array[], int num) {
int squareR = (int)sqrt(num);
for(int i = 2; i <= squareR; ++i){
int k;
if(array[i]){
for(k = i*i; k <= num; k += i)
array[k] = 0;
}
if (array[i] == 1){
array[i] = i;
}
}
}
void goldbach(int array[], int num){
int i, r = 0;
for (i = 4; i <= num; i += 2){
for (int j = 2; j <= i/2; j++)
if (array[j] && array[i-j]) r ++;
}
}
my problem is that it displays numbers higher than 1,000 as 1s, how can I go about this
That's because you're not updating the values in the array above 1000, here:
for(int i = 2; i <= squareR; ++i){
...
if (array[i] == 1){
array[i] = i;
clearly the array's entries above squareR are not updated and remain at the value you initialized them, which is 1.
However I you don't need this update at all. You can drop it and simplify your code, keeping the array's entries as either 1 (for primes) or 0 (for non-primes). with this, and display your result like this (in main):
for(int i = 0; i < arraySize; ++i){
if (nums[i] != 0){
// cout << nums[i] << " "; // <-- drop this
cout << i << " "; // <-- use this
}
}
I tried to calculate average and when I enter 1 2 3 0 , the average is 2.00 but when I enter 10 20 90 100 0,the average is 227871776.00. I am not able to identify what is going wrong here. I feel like my sum and count is not working properly but I can't figure out why.
double calculateAverage(int numbers[], int count )
{
int sum = 0;
double average;
while (count < arraysize && numbers[count] != 0)
{
count ++;
}
for (int i= 0 ; i < count; i++)
{
sum += numbers[i];
}
average = static_cast<double>(sum) /count;
return average;
}
Why bother even making your own count loop, when you have std:accumulate.
#include <numeric>
#include <iostream>
double calculateAverage(int numbers[], size_t count)
{
int sum = std::accumulate(numbers, numbers + count, 0);
return sum / count;
}
int main()
{
//int numbers[] = {1, 2, 3, 4, 5};
int numbers[] = {10, 20, 90, 100};
std::cout << "average is " <<
calculateAverage(numbers, sizeof(numbers) / sizeof(int)) << '\n';
}
Your code was quite confused. Why pass a count if you're going to count the array anyway? Also 0 is a valid value in the array and so it makes a flawed sentinel value.
#include<iostream>
using namespace std;
double calculateAverage(int numbers[], int count )
{
int sum = 0; //sum is used to add all the values in the array
double average;
for (int i= 0 ; i < count; i++)
sum += numbers[i];
average = static_cast<double>(sum) /count;
return average;
}
int main()
{
int lim; //size of the array
cout<<"Enter the number of elements in array\n";
cin>>lim;
cout<<"Enter the values \n";
int num[lim]; //the array is initialized to desired size
for(int i=0;i<lim;i++)
cin>>num[i]; //the values are taken from user
cout<<"\nAverage = "<<calculateAverage(num,lim)<<"\n"; //the array and the size of array is passed to calculate average function or you can even calculate size of array using (sizeof(array)/sizeof(array[firstelement])
return 0;
}
Recreate the code overall
It is hard to understand (your code).
Mine:
double calculateAverage(double numbers[], double count )
{
double sum = 0;
double average=0;
for(int counter=0;counter<count;counter++)
{
sum+=numbers[counter];
}
cout<<sum<<"\n";
average=sum/count;
return average;
}
Explaination:
First the function will take an array of double
and count is how many is there in the array (I tried to stick into your code)
The for loop runs based on the count variable.
the sum adds the value of the element in the array numbers.
Divide to get the average.
numbers[count] != 0 could produce errors when you have 0 appear earlier in the array. Also, where do you initialize arraysize? It could be null somehow or a very weird number. I recommend calling the numbers length instead. But there's no reason to use the while loop bc you have an array size already known