C++ function does not execute in the main section - c++

I am having difficulties with a program that does not execute a function and i cant seem to find the problem.
This little piece of code that I'm trying to write should ask the user to enter the size of the 2d array and after that search each row and calculate the average of the rows.
It executes just fine until the calculation results come up.
The example:
Enter the size of the array: 2
2
Enter the element of the 1 row and 1 column: 10
Enter the element of the 1 row and 2 column: 20
Enter the element of the 2 row and 1 column: 50
Enter the element of the 2 row and 2 column: 20
Program ended with exit code: 0
and code of the program:
#include <iostream>
#include <iomanip>
using namespace std;
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k); //to calculate the average of each row
void input(int n, int m, int matrix[10][10]); //to input the requirements
void results(double avg[10],int n); //to output the results
int main() {
int matrix[10][10]; //the array
int n,m; //rows and columns entered by the user
double avg[10]; //average of the array rows, which will be calculated later
int k; //number of positive elements
double sum; //to calculate sum
input(n, m, matrix);
calculate(n, m, matrix, sum, avg, k);
results(avg, n);
return 0;
}
void input(int n, int m, int matrix[10][10]) {
cout<<"Enter the size of the array: ";
cin>>n>>m; //the real elements of the array
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cout<<"Enter the element of the "<<i+1<<" row and "<<j+1<<" column: "; //entering each element of the array
cin>>matrix[i][j];
}
}
}
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k) {
for (int i=0; i<n; i++) {
k=0;
sum=0;
avg=0;
for (int j=0; j<m; j++) {
if (matrix[i][j]>0) {
sum+=static_cast<double>(matrix[i][j]);
k++;
}
}
if (k>0) {
avg[i]=sum/static_cast<double>(k);
}
}
}
void results(double avg[10], int n) {
for (int i=0; i<n; i++) { //
cout<<"Average of "<<i<<" row is equal to: "<<avg[i]<<"\n";
}
}

There are multiple problems with your code:
You ask the user for the size of your array, but you have the array defined with constant size:
int matrix[10][10];
What would happen if user entered 11? It would result in an undefined behavior. Consider using std::vector if you want to have truly dynamic arrays.
When you read your n, m values inside void input(int n, int m, int matrix[10][10]) procedure, you are making changes to the copies of those variables (i.e. they are passed by value), so, the changes are only visible to the inside of the function. When you leave the scope of that function, all changes you did to them, are lost. You need to pass those parameters by reference, i.e.:
void input(int& n, int& m, int matrix[10][10]);
That way, the compiler won't do a copy, and you will be changing the same variables from your main.
Having that in mind, you would need to change your calculate procedure in a similar way:
void calculate(int n, int m, int matrix[10][10], double& sum, double avg[10], int& k);
No need for variables n, and m to be passed by reference, since, in this case, they are input parameters, and don't need to be changed.

You are not changing n and m in main(). input() takes in the parameters by value which mean it makes a copy so the changes done in the function are local only to the function. To fix this just pass n and m by reference.
void input(int& n, int& m, int matrix[10][10])

Related

check if the array can be split to subarrays which are equal in sum

my problem i face is i cant run my code when i use cin>>arr
can i make it work with this code
#include <bits/stdc++.h>
using namespace std;
int checkEqualSumUtil(int arr[1000], int N,
int sm1, int sm2,
int sm3, int j)
{
if (j == N)
{
if (sm1 == sm2 && sm2 == sm3)
return 1;
else
return 0;
}
else
{
int l = checkEqualSumUtil(arr, N,
sm1 + arr[j],
sm2, sm3, j + 1);
int m = checkEqualSumUtil(arr, N, sm1,
sm2 + arr[j],
sm3, j + 1);
int r = checkEqualSumUtil(arr, N, sm1, sm2,
sm3 + arr[j], j + 1);
return max(max(l, m), r);
}
}
void checkEqualSum(int arr[], int N)
{
int sum1, sum2, sum3;
sum1 = sum2 = sum3 = 0;
if (checkEqualSumUtil(arr, N, sum1,
sum2, sum3, 0)== 1)
{
cout << "YES";
}
else
{
cout << "NO";
}
}
int main()
{
int n;
cin>>n;
int arr[n/2];
for(int i=0;i<n;i++){
cin>>arr[i];
int N = sizeof(arr) / sizeof(arr[0]);
checkEqualSum(arr, N);
return 0;
}}
my code
i have edited my code the input is typed correctly
but it always outputs no
i dont know why any ideas??
also thank you for helping me all
i tried the input
3
1 1 1
it should print yes
put the output is no?
Let's analyze your code in main:
int main()
{
int arr[1000],n;
You have allocated an array, arr, that has a capacity of 1000 integers.
The array is not initialized.
An alternative declaration:
const unsigned int N = 1000;
int array[N];
The statement below reads the quantity of numbers to read into the array.
cin>>n;
If the User or Operator enters a value larger than 1000, you will have undefined behavior. Quantities less than 1000 are a waste of space. Use std::vector<int> to contain elements when the capacity is not known during runtime.
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
Here you are calculating the capacity of the array. The capacity was already declared as 1000. See my suggestion about using N as the capacity.
int N = sizeof(arr) / sizeof(arr[0]);
The above line is not necessary. Another option is to use a macro:
#define MAXIMUM_NUMBERS (1000)
The present form of the statement below, tells the function to use 1000 values, regardless of the quantity of numbers entered by the User.
checkEqualSum(arr, N);
For example, if I enter 5 numbers, the function call will translate to:
checkEqualSum(arr, 1000);
This because you initialized N to the capacity of the array.
Maybe you want to pass the quantity of numbers read into the array:
checkEqualSum(arr, n);
This is why variable names should differ in more than case.
This code is fine, telling the Operating System that your code run with no errors.
return 0;
}

Trying to save different values in 2 arrays using one FOR loop but the first array is been attributed the value of the second input

I am testing the ability to use functions to input values in 2 arrays and also to perform addition of the values. I wish to input the different values in the 2 arrays using a function inputArray(A1, A2, size) using a For loop.
I also used a function sumArray(A1, A2, size) to perform the addition of the 2 values in the arrays.
But the issue is with the input function as when i am running the program to input different values in the 2 arrays, the first array is also been attributed the value of the second array.
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
I tried to use 2 different functions to input the values and this worked.But then again when i used a FOR loop for the Addition function sum = sumArray(A1, A2, size), both arrays A1 and A2 were being attributed the value of the second array.
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
#include<iostream>
using namespace std;
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
//To sum all the values in the 2 arrays//not asked in the question
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
int main()
{
int size;
int A1[size];
int A2[size];
size= 3;
cout<<"Input "<<size<<" values in the first and second array: "<<endl;
inputArray( A1, A2, size); //do not write square bracket when calling a function
int sum = sumArray(A1, A2, size);
cout<<"The sum of the total values is : "<<sum<<endl;
//test
cout<<"\n\t A1[0]= "<<A1[0]<<endl;
cout<<"\n\t A2[1]="<<A2[2]<<endl;
return 0;
}
Here you use a non-initialised variable for the size of the two arrays.
int size;
int A1[size];
int A2[size];
This is in C++ wrong in more than one way.
You need to define C-like arrays with a constant size.
Safer would be to use C++ containers, e.g. std::vector for anything without predictable size.
Even in C, where VLAs are possible, creating them like you did and LATER reading in a new value for size will not change anything, especially not the size of the arrays.
Also, but that is already inside undefined behaviour and purely speculative,
if the compiler understands that as A1 and A2of size 0, then the start of both arrays is the same and writing to one writes also to the other - AND be totally forbidden because it will access beyond any arrays size.
To demonstrate that, try
int A1[5];
int A2[5];

The output of this question is correct but i am getting a segmentation error

I am trying to solve the program of array rotation. I am getting segmentation error in the code. Can someone please tell where is the problem in this code?
this is the question
Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).
The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.
and i have solved it with the following code.
#include <iostream>
using namespace std;
int* rotate(int ar[],int n, int m)
{static int temp[100];
for(int i =0;i<m;i++)
{
temp[i]=ar[i];
}
for(int j =m;j<n;j++)
{
ar[j-m]=ar[j];
}
int x=0;
for(int k =n-m;k<n;k++)
{
ar[k]=temp[x];
x++;
}
return ar;
}
int main() {
//code
int t, n , m;
cin>>t;
while(t>0)
{
cin>>n>>m;
int arr[n];
int * ptr;
for(int i = 0 ;i<n;i++)
{
cin>>arr[i];
}
ptr=rotate(arr,n,m);
for(int j=0;j<n;j++)
cout<<ptr[j]<<" ";
cout<<endl;
t--;
}
return 0;
}
If m > n then it crashes in the first for() loop in rotate as you index past the end of arr.
If m < 0 it crashes in the 2nd loop as it index before arr.
There are probably more cases.

Jordans elimination float to float argument

So I was trying to work on a code about Jordan's elimination. When I encountered a problem:
Cannot convert 'float' to 'float ()[100]' for argument '1' to 'int diabase(float ()[100])
What does this mean? And how can I fix it?
#include<stdio.h>
#define N 100
int read(float A[N][N]);
int jordan(float A[N][N],int n);
int print(float A[N][N],int n);
int main()
{
int i, j, k, n, y;
float A[N][N+1], c, x[N];
n = read(A[N][N]);
jordan(A[N][N]], n);
print(A[N][N], n);
return(0);
}
int read(float A[N][N]){
int n,i,j;
printf("Enter the size of matrix: ");
scanf("%d",&n);
printf("Enter the elements of augmented matrix row-wise:");
for(i=1; i<=n; i++)
{
for(j=1; j<=(n+1); j++)
{
printf(" A[%d][%d]:", i,j);
scanf("%f",&A[i][j]);
}
}
return n;
}
int print( float A[N][N],int n){
int i;
float x[n];
printf("The solution is:");
for(i=1; i<=n; i++)
{
x[i]=A[i][n+1]/A[i][i];
printf("n x%d=%fn",i,x[i]);
}
return 0;
}
int jordan(float A[N][N],int n){
int i,j,k;
float c;
for(j=1; j<=n; j++)
{
for(i=1; i<=n; i++)
{
if(i!=j)
{
c=A[i][j]/A[j][j];
for(k=1; k<=n+1; k++)
{
A[i][k]=A[i][k]-c*A[j][k];
}
}
}
}
return 0;
}
In all of these function calls
n=read(A[N][N]);
jordan(A[N][N]],n);
print(A[N][N],n);
You are passing and element of the array instead of the array. If you want to pass the array you just use the name of the array without any indexes
n=read(A);
jordan(A,n);
print(A,n);
You are going to run into another problem with this though as your functions expect a 2d array of 100 x 100 but your array you created in main() is 100 x 101 which is not going to match. You either need to make the array in main() 100 x 100 or change you function take arrays of 100 x 101
When you do function (A[N][N]) you are passing a single float value to function, so here:
n = read(A[N][N]);
jordan(A[N][N], n);
print(A[N][N], n);
You are passing single values to read, jordan and print. And B.T.W you are accessing cells that do not exist (A[N] is out of bound since A is float [N][N + 1].
If you want to pass A to your function, simply do:
n = read(A);
jordan(A, n);
print(A, n);
Apart from that, there are some mistakes in your code:
Your functions want a float [N][N] but A is float [N][N+1] so you will have to modify something.
You are accessing cells from 1 to n/n+1, C arrays have cells from 0 to n-1/n, so your loop should go from 0 to n-1/n.
Your main should be
int main()
{
float A[N][N];
int n = read(A);
jordan(A, n);
print(A, n);
return(0);
}

Array Manipulation C++

I am trying to create a code that reads in an array, finds the smallest element in that array, and then subtracts that smallest element from all the other elements in the array and prints a new array with these elements.
The code I have written so far will not even compile.
Here is what I have:
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE(25);
void read_list(int a[], int&num_ele);
void print_array(const int a[], const int num_ele);
int find_min(const int a[], const int num_ele);
void array_subtract(int x, int&a[], int num_ele) ;
int main()
{
int num_ele(0);
int array[SIZE] ;
read_list(array, num_ele);
cout<<"Before list: ("<<num_ele<< " numbers): " <<endl;
print_array(array, num_ele) ;
min = find_min(array, num_ele) ;
cout<<"The minimum value = "<<min<<endl;
array_subtract(min ,array ,num_ele) ;
cout<<"After list: ("<<num_ele<< " numbers): " <<endl;
print_array(array, num_ele) ;
return 0;
}
void read_list(int a[], int&num_ele)
{
int x(0);
cout<<"Enter positive numbers (ints) terminated 0: "<<endl;
cin>>x;
while(x!=0 && num_ele <= SIZE)
{
a[num_ele] = x ;
num_ele++;
cin >> x;
}
}
void print_array(const int a[], const int num_ele)
{
for(int i=0; i<num_ele; i++)
{
if(i<num_ele-1)
{cout<<a[i]<<", "; }
else
{cout<<a[i]<<"."}
}
}
int find_min(const int a[], const int num_ele)
{
int x= a[0];
for(int k=0; k<num_ele; k++)
{
if(a[k] < x)
{ x=a[k] ;}
}
return x ;
}
void array_subtract(int x, int&a[], int num_ele)
{
for(int j=0; j<num_ele; j++)
{
a[j] = a[j]-x ;
}
}
When I go to compile, at the line
cout<<"The minimum value = "<<min<<endl;
I get about 100 lines of errors.
Is there some huge error in my code I am missing? Why would this happen? I would like to keep the code in the same format it is in (calling functions to get the final output).
Thanks
You have 3 problems, after correcting these problems, at least you have not compile errors.
i.
You're passing arrays wrong:
void array_subtract(int x, int&a[], int num_ele);
^^^^^^^
Pass it like below (remove &)
void array_subtract(int x, int a[], int num_ele);
ii.
You're using variable min without declaring it. Declare it like below:
int min;
iii.
You've missed a semicolon ; in function print_array:
cout<<a[i]<<".";
^
You did not define variable min so the compiler reports errors when encounters statement
min = find_min(array, num_ele) ;
Aside from the compilation errors addressed by others...
Instead of using an array, use a vector (since logically you array is variably sized from 0-SIZE, and a vector is a variable sized array)...
vector<int> v;
Accept integer input until 0 is typed...
for(int n; cin >> n && n != 0;)
v.push_back(n);
Find the min element...
auto min = min_element(begin(v), end(v));
Printing can be done a variety of ways...
cout << "Vector: [";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << "]\n";
Subtract the min from the elements...
transform(v.begin(), v.end(), v.begin(), [min](int n){ return n-min; });
Try to use the C++ standard library when possible instead of hand rolling loops. It reduces the potential for bugs, and is often clearer (but not always... for example that print I posted above doesn't exactly read intuitively IMO)