Unknown compiler error in cout<< theoreticlly it works - c++

#include <iostream>
using namespace std;
void matrice(int n){
cout<<"Input the number of the elements "<<endl;
cin>>n;
int D[n][n];
cout<<"Input the elements :";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>D[i][j];
}
}
int min;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if( min=0>D[i-1][j-1]){
D[i-1][j-1]=min;
}
}
}
cout<<" The smallest element is : "<< min<<"and it is the"<< i <<" element ." ;
}
int main(){
int i, min ,j,n;
int n1;
cout<<"Decide: "<<endl;
cout<<"Matrice[1]"<<"\t"<<"Vekcor[2]"<<endl;
cin>>n1;
if(n1==1){
matrice(n);
}
else if(n1==2){
}
}
The problem is at line 22 at the cout and it gives this message:
C:\Users\use\Documents\Dev C++\void_vektor.cpp|22|error: no match for 'operator<<' (operand types are 'std::basic_ostream' and '')|

min is only visible in for loop scope because you have declared it inside of loop.
declared it here:
int min=D[0][0];
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (min > D[i - 1][j - 1])
{
D[i - 1][j - 1] = min;
}
}
}
cout << " Elementi me i vogel eshte : " << min;
also note that you have used uninitialized n in main and even though you will take it as input in function sending an uninitialized variable to a function might be problematic.
and also move declaration of int D[n][n]; after taking n as input.
cout<<"Input the number of the elements "<<endl;
cin>>n;
int D[n][n];
instead of your loops I suggest this which is easier:
int min=D[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (min > D[i][j])
{
D[i][j] = min;
}
}
}
cout << " Elementi me i vogel eshte : " << min;
also note that if you initialize min=0 you can't find min in array in which all of elements>0. I suggest min=[0][0].

The main issue is that you declare min inside the for loop, it will go out of scope as the loop exits.
The bizarre error message is likely because of the std::min function. This is a good case study on why not to use using namespace std;.
At first glance there are other issues in your code:
i, min and jare unused in main().
n is used uninitialized, this is undefined behaviour, furthermore C++ forbids variable-size array. If you need a variable length array you can use something like std::vector.
if(min = 0 > D[i-1][j-1]) is very strange, is that really what you need?
In the future you should use compiler warnings.

There's a fundamental problem here: the call matrice(n) in main uses the uninitialized value of n, so if your compiler supports that int D[n][n] syntax you have no idea how large the array actually is. Formally, the behavior is undefined. Informally, there's a 50/50 chance that you'll get a negative number, which doesn't make sense as an array size.

Related

i am only getting the output right if i say i is int specially in for loop

#include <iostream>
using namespace std;
// finding the required sum of subarray
int main()
{
int n,s;
int i=0,j=0,st=-1,en=-1,sum=0;
cin>>s; //input required sum
cin>>n;
int a[n];
for(int i=0;i<n;i++){ // here if i only mention int again i //am getting the output or else the values of st and en are printing //out the same as i initialize
cin>>a[i];
}
while (j<n){
sum+=a[j];
while(sum>s){
sum-=a[i];
i++;
}
if(sum==s){
st=i+1;
en=j+1;
break;
}
j++;
}
cout<<st<<" "<<en<<" ";
return 0;
the output is -1 -1
and if i mention "int i" again in for loop of inputing array i a getting the answer.
i want to know the reason i already intialize i before why do i need to do it again
The problem statement is unclear, I'm assuming you simply want the indexes of the repeating numbers in array a. You are correct for the most part, using b[i] = i is the problem. If you understand what a vector is, then simply create a vector like this and push the indexes in the vector. For example,
vector<int> b;
and inside the a[i] == a[j] condition,
b.push_back(i);
then finally print out result like,
for(int i = 0 ; i < b.size() , i++)
cout << b[i] << " ";
If you're unfamiliar with vectors, simply use another variable cnt to update index of array b
int a[n], i, b[n], j, cnt = 0;
and inside the a[i] == a[j] condition,
b[cnt] = i;
cnt++;
and finally
for(int i = 0 ; i < cnt ; i++)
cout << b[i] << ' ';

C++ code don't have errors but not giving output [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 last year.
Improve this question
I am writing code for selection sort in c++. It gives no error when i compile it with the command g++ main.cpp -o main in powershell but when i run the code with ./main, it don't show anything. I tried with hello world program and it worked. I don't know why the selection sort code not working.
Here Is the code of Selection sort
#include<iostream>
using namespace std;
int main()
{
int n, a[n];
cout << "Enter the size of the array = ";
cin >> n;
cout << "Enter the numbers :" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
for (int i = 0; i < n-1; i++)
{
for (int j = i+1; j < n; j++)
{
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int b=0; b<n; b++)
{
cout<<a[b];
}
return 0;
}
There are 2 problems in your program.
Mistake 1
In Standard C++ the size of an array must be a compile time constant. So take for example,
int n = 10;
int arr[n] ; //INCORRECT because n is not a constant expression
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Mistake 2
You're using an uninitialized variable which leads to undefined behavior. In particular when you wrote:
int n, a[n]; //here variable n is uninitialized and holds **indeterminate value**.
In the above statement, you are creating an int named n but since you have not explicitly initialized it, it holds an indeterminate value.
Next, you're using that garbage value as the size of the array a. But note that using uninitialized variable results in undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
This is why it is advised that
always initialize built in types in local/block scope.
Solution
A better way would be to use std::vector as shown below.
#include <iostream>
#include <vector>
int main()
{
int n = 0; //always initialize built in types in local/block scope
std::cout<<"Enter size: "<<std::endl;
std::cin >> n;
//create a vector of size n
std::vector<int> a(n);
//iterate and ask for input
for(int i = 0; i < a.size(); ++i)
{
std::cout<<"Enter element: "<<std::endl;
std::cin >> a[i];
}
for (int i = 0; i < a.size() - 1; ++i)
{
int index = i;
for (int j = i + 1; j < a.size(); j++) {
if (a[j] < a[index])
index = j;
}
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
std::cout<<"The elements of the vector are:"<<std::endl;
//print the element of the vector
for(const int& elem: a)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the program can be seen here.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
Always initialize variables. A declaration without initialization is a code smell, eg this one:
int n;
The issue immediately follows, because
int n, a[n];
uses n uninitialized. Compilers do a pretty good job at warning about this: https://godbolt.org/z/ErPY3x936. Before you initialize n, it has an indeterminate value. Using its value leads to undefined behavior. Further, a[n] is a variable length array (unless n is a constant expression), which is not part of standard C++. When you need an array whose size is only known at runtime, you can use a std::vector:
int n = 0;
cout << "Enter the size of the array = ";
cin >> n;
std::vector<int> arr(n);
You are trying to use a variable length array
int n, a[n];
Variable length arrays is nit a standard C++ feature. So you should avoid to use them. Instead use the standard container std::vector<int>.
Moreover the variable n is not initialized. So the declaration of the variable length array invokes undefined behavior.
Within the for loops where you are sorting the array there are too many swaps of elements of the array.
The selection sort algorithm assumes that a selected element in an array is swapped at most one time.
And there is the standard function std::swap that can be used instead of manually swapping elements.
Your program can look the following way
#include <iostream>
#include <utility>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of the array (0 - exit): ";
std::cin >> n;
if ( n )
{
std::vector<int> v( n );
std::cout << "Enter the numbers :" << std::endl;
for ( auto &item : v )
{
std::cin >> item;
}
for ( std::vector<int>::size_type i = 0; i < v.size(); i++ )
{
auto min = i;
for ( auto j = i + 1; j < v.size(); j++ )
{
if ( v[j] < v[min] ) min = j;
}
if ( min != i ) std::swap( v[min], v[i] );
}
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << std::endl;
}
return 0;
}.

Error:No matching function for call to

I am very very new to C++ and I am trying to call the function "jacobi" which performs a user specified number of iterations for the jacobi method (or at least I hope so). On the line where I call 'jacobi' I get the error "No matching function to call to "jacobi". I have read other posts similar to this one and have tried to apply it to my own code but I have been unsuccessful. Maybe there are other issues in my code causing this problem. As mentioned I am very new C++ so any help would be appreciated and please break it down for me.
#include <iostream>
using namespace std;
void jacobi (int size, int max, int B[size], int A[size][size], int init[size], int x[size]){
////
//// JACOBI
////
int i,j,k,sum[size];
k = 1;
while (k <= max) // Only continue to max number of iterations
{
for (i = 0; i < size; i++)
{
sum[i] = B[i];
for (j = 0; j < size; j++)
{
if (i != j)
{
sum[i] = sum[i] - A[i][j] * init[j]; // summation
}
}
}
for (i = 0; i < size; i++) ////HERE LIES THE DIFFERENCE BETWEEN Guass-Seidel and Jacobi
{
x[i] = sum[i]/A[i][i]; // divide summation by a[i][i]
init[i] = x[i]; //use new_x(k+1) as init_x(k) for next iteration
}
k++;
}
cout << "Jacobi Approximation to "<<k-1<<" iterations is: \n";
for(i=0;i<size;i++)
{
cout <<x[i]<< "\n"; // print found approximation.
}
cout << "\n";
return;
}
int main (){
// User INPUT
// n: number of equations and unknowns
int n;
cout << "Enter the number of equations: \n";
cin >> n;
// Nmax: max number of iterations
int Nmax;
cout << "Enter max number of interations: \n";
cin >> Nmax;
// int tol;
// cout << "Enter the tolerance level: " ;
// cin >> tol;
// b[n] and a[n][n]: array of coefficients of 'A' and array of int 'b'
int b[n];
int i,j;
cout << "Enter 'b' of Ax = b, separated by a space: \n";
for (i = 0; i < n; i++)
{
cin >> b[i];
}
// user enters coefficients and builds matrix
int a[n][n];
int init_x[n],new_x[n];
cout << "Enter matrix coefficients or 'A' of Ax = b, by row and separate by a space: \n";
for (i = 0; i < n; i++)
{
init_x[i] = 0;
new_x[i] = 0;
for (j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
jacobi (n, Nmax, b, a, init_x, new_x);
}
The problem:
There are several problems, related to the use of arrays:
You can't pass arrays as parameter by value.
You can't pass multidimensional arrays as parameter if the dimensions are variable
You can't define arrays of variable length in C++
Of course there are ways to do all these kind of things, but it uses different principles (dynamic allocation, use of pointers) and requires additional work (especially for the access of multidimensional array elements).
Fortunately, there is a much easier solution also !
The solution:
For this kind of code you should go for vector : these manage variable length and can be passed by value.
For the jacobi() function, all you have to do is to change its definition:
void jacobi(int size, int max, vector<int> B, vector<vector<int>> A, vector<int> init, vector<int> x) {
int i, j, k;
vector<int> sum(size); // vector of 'size' empty elements
// The rest of the function will work unchanged
...
}
Attention however: the vectors can be of variable size and this jacobio implementation assumes that all the vectors are of the expected size. In professional level code you should check that it's the case.
For the implementation of main(), the code is almost unchanged. All you have to do is to replace array definitions by vector definitions:
...
vector<int> b(n); // creates a vector that is initialized with n elements.
...
vector<vector<int>> a(n,vector<int>(n)); // same idea for 2 dimensional vector (i.e. a vector of vectors)
vector<int> init_x(n), new_x(n); // same principle as for b
...

Weird Array Stuff (Array indexes getting values without me setting it)

I am trying to write a sudoku solver.
I got the input almost done, but something strange started happening. On the index [i][9] of int sudoku[i][9], there are numbers present that I have never put there.
For example, when I run the code below with the input that is commented below using namespace std;, the output is:
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
Of course, I only need 0 through 8, but I was wondering what is causing integers to appear at the 9th index.
This is the code:
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/*
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
*/
int main()
{
int sudoku[9][9];
int solving[9][9][9];
int input;
for (int i=0; i<=8; i++) {
cin >> input;
int j;
int k;
for (j=8, k=1; j>=0; j--, k++) {
int asdf = input/pow(10,k-1);
sudoku[i][j] = asdf % 10;
}
}
cout << endl;
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku[i][j];
}
cout << endl;
}
return 0;
}
Accessing elements outside of the defined region of an array is Undefined Behavior (UB).
That means it could:
Allow you to access uninitialized space (what yours is doing hence the random numbers)
Segfault
Any number of other random things.
Basically don't do it.
In fact stop yourself from being able to do it. Replace those arrays with std::vectors and use the .at() call.
for example:
std::vector<std::vector<int>> sudoku(9, std::vector<int>(9, 0));
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku.at(i).at(j);
}
cout << endl;
}
Then you will get a thrown runtime exception that explains your problem instead of random integers or segfaults.
I think I found your problem, at your very last for loop you used j <= 9 instead of j <= 8. You then tried to write (j) leaving the possibility of it writing 9 wide open. Try replacing that 9 with 8.

Arrays homework question

I have this homework question:
Write and test a program that read in n integers (max value for n is 20), each integer has
a value between 0 and 100 inclusive. You program should then print out the unique values
among the input numbers and the count of these values.
Sample input:
Enter a the number of integers = 8
Enter 8 integers: 5 6 7 6 6 17 17 35
Sample output:
Number 5: 1
Number 6: 3
Number 7: 1
Number 17: 2
Number 35: 1
This is what I did:
#include<iostream>
using namespace std;
int main(){
int a[20], n;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
cin >> a[i];
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++){
if (a[i]==a[k])
sum= sum+1;
}
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
}
Consider that when you iterate through your list, you're checking all values with both i and k. So essentially, if you had a list of 1 1 2 2, then the first one will count itself, and the 1 at a[1]. The second 1 will count the first 1 and itself, giving you your repeated output.
A way to simplify this would be to make use of a hash_map, or some similar structure (I'm not as familiar with C++) that maps a key to a value and doesn't allow repeats. This would allow you to record the unique numbers as keys, and increment them with only one pass through the list. The advantage to using the hashMap is that you make your program linear (although I don't think that's really a concern at this stage).
The simplest way to solve your problem, however would be to use a Bin sort technique. The underlying idea here is that your number range is simply 0 to 100, meaning you could create bins for 0 to 100 and increment each one. Again, this is Java code, and doesn't have any actual input for a.
// Count is the key, it uses indexes from 0 to 100, with null values of
// 0 after initialized. Simply iterate the loop, and use the value of
// a[k] to increment the corresponding count in the count array.
// Finally, print the results
int[] a = new int[20];
int[] count = new int [101];
for (int k = 0; k < a.length; k++){
count[a[k]]++;
for (int i = 0; i < count.length; i++){
if (count[i] > 0)
System.out.println(i + ": " + count[i]);
}
Add another bool b[20] ,initialize it with true. Then every time you detect a[k] is a dupe, you set b[k] = false. Only print a[k] if b[k] == true
for (int k = 0; k < n; k++) {
if (!b[k]) {
continue;
}
int sum = 0;
for (int i = 0; i < n; i++) {
if (a[i] == a[k]) {
sum = sum + 1;
b[i] = false;
}
}
cout << "Number " << a[k] << " : " << sum << endl;
}
You have to keep a running count of the items you processed in a separate array, and before running your inner loop to count the items, check if he item you're trying to count isn't in your second array already.
Before you print the result, check if you already printed it for this number
Here's my new attempt.
A quick fix (while not the most professional) would be to create another loop checking for repeats right before printing out.
I took your current big loop and turned it into an even bigger monster.
I also tested it out and it works for me. =D
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++)
{
if (a[i]==a[k])
sum= sum+1;
}
bool repeat = false;
for(int i = 0; i < k; i++)
{
if(a[k] == a[i])
{
repeat = true;
}
}
if(!repeat)
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
An alternate implementation (and more memory-hungry with your current limit of 20 input values) would be to create an array of 100 "count" values. Increment the appropriate item for each input value, then iterate through the count array outputting non-zero values.
Apparently that description wasn't good enough... perhaps some code would help (NOTE:This code is untested, but should be enough for you to understand the concept):
#include<iostream>
using namespace std;
int main(){
int a[101], n, v;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
{
cin >> v;
a[v] ++;
}
for (int k=0; k< 100; k++){
if (a[k] > 0)
{
cout<< "Number "<< k + 1 <<" : "<< a[k] << endl;
}
}
}
}
getting familiar with Standart Template Library is the key to writing good programs in my humble opinion, since this is a homework, you do the controlling for 0 and 100 ;-))
#include <iostream>
#include <map>
using std::cin;
using std::map;
using std::cout;
using std::endl;
int main()
{
int limit = 20;
int cnt=0;
int n;
map<int, int> counters;
while( cnt++ < limit )
{
cin >> n;
++counters[n];
}
for(map<int, int>::iterator it = counters.begin();
it!=counters.end(); ++ it)
cout << it->first << " " << it->second << endl;
return 0;
}