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;
}.
Related
#include <iostream>
using namespace std;
void value(int array[],int size){
int minimum;
int maximum;
minimum = array[0];
for(int x = 0; x < size; x++){
if(minimum > array[x+1]){
minimum = array[x+1];
}
}
maximum = array[0];
for(int x = 0; x < size; x++){
if(maximum < array[x+1]){
maximum = array[x+1];
}
}
cout << "Minimum Value is: " << minimum << endl;
cout << "Maximum Value is: " << maximum;
}
int main(){
int size;
cout << "Number of values you want to input: ";
cin >> size;
cout << "Input " << size << " values" << endl;
int array[size];
for(int x = 0; x < size; x++){
cout << "Input #" << x+1 <<": ";
cin >> array[x];
}
value(array,size);
return 0;
How can I output the maximum value inside the array? whenever I print the value the maximum value always return a number that is not present inside the array but the minimum seems fine, its only the maximum value that I am encountering a problem, I tried every possible answer that I know but it doesn't work, I hope ya'll can help Thank you in advance
for(int x = 0; x < size; x++){
If you have an array with ten values, size will be 10. If you work out, with paper and pencil, what this for loop does, you will see that it iterates for values of x 0 through 9, that's what this says. x starts with 0. When it reaches 10, x < size will be false and the loop ends, so the loop runs with x ranging from 0 to 9.
if(minimum > array[x+1]){
Since x will range from 0-9, it logically follows that x+1 will range from 1 to 10, and so this if statement will check the values in array[1] through array[10].
In C++ array indexes start with 0, not 1. The values in your array are array[0] through array[9]. array[10] does not exist, so the above code is undefined behavior.
Furthermore:
int array[size];
This is not valid C++ either. Your C++ compiler may allow this as a non-standard C++ extension, but array sizes must be fixed, constant sizes in C++, determined at compile time. You can't use a non-constant variable to set the size of an array, C++ does not work this way. If you need to have an array of size that's determined at runtime then you need to use std::vector instead of a plain array, and change the rest of your code accordingly.
Mistake 1
Your example has undefined behavior because of the expression array[x+1]. That is, for the last iteration of the for loop, you're going out of bounds of the array and so have 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.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
In standard C++, the size of an array must be a compile time constant. So in your code:
int size;
cin >> size;
int array[size]; //NOT STANDARD C++
The statement int array[size]; is not standard C++ because size is not a constant expression.
Additionally you don't need 2 separate for loops when you can achieve the goal in 1 for loop as shown below.
Solution 1
You can use std::vector as shown below:
#include <iostream>
#include <vector>
#include <climits>
//this function take a vector as input
void value(const std::vector<int>& arr)
{
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the vector to find the max and min value
for(const int& element: arr)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num; //return the difference of mx and min value
}
int main()
{
int n;
std::cout<<"elements: ";
std::cin >> n;
//create vector of int of size n
std::vector<int> arr(n);
//take elements from user
for(int i=0; i<n; i++)
{
std::cin >> arr[i];
}
value(arr);
return 0;
}
Demo
Solution 2
You can make the function a function template so that you don't need to pass a separate argument to the function as shown below:
#include <iostream>
#include <climits>
//N is a nontype template parameter
template<std::size_t N>
void value(const int (&array)[N]){
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the array to find the max and min value
for(const int& element: array)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num;
}
int main(){
int array[3] = {};
for(int x = 0; x < sizeof (array) / (sizeof (array[0])); x++){
std::cout << "Input #" << x+1 <<": ";
std::cin >> array[x];
}
value(array); //no need to pass the second argument
return 0;
}
Demo
Also note that with C++17, you can use std::size instead of sizeof (array) / (sizeof (array[0])) to find the length of the array.
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.
As I'm new to c++ I get runtime error for first example(I mean I tested my program with 5 examples it actually happens automatically by a site for testing) of my program I know that's because of exceeding time for running it but I dunno how to fix this.
My program get n numbers from user and finds the largest one and prints it.
#include<iostream>
#include<curses.h>
using namespace std;
int main()
{
int n;
cin >> n;
int *p = new int(n);
for(int i = 1; i<=n; i++){
cin >> *(p+i);
}
int largest = *p;
for(int i = 1; i<=n; i++){
if(largest < *(p+i))
largest = *(p+i);
}
cout << largest;
return(0);
}
int *p=new int(n);
The line above allocates just a single int, and sets the value to n. It does not allocate an array of n integers.
That line should be:
int *p=new int[n];
And then delete [] p; to deallocate the memory.
But better yet:
#include <vector>
//...
std::vector<int> p(n);
is the preferred way to utilize dynamic arrays in C++.
Then the input loop would simply be:
for(int i=0;i<n; i++)
{
cin >> p[i];
}
That same input loop could have been used if you had used the pointer version.
Then you have this error:
for(int i=1;i<=n;i++)
Arrays (and vectors) are indexed starting from 0 with the upper index at n-1, where n is the total number of elements. That loop has an off-by-one error, where it exceeds the upper index on the last loop.
Basically any loop that uses <= as the limiting condition is suspect. That line should be:
for(int i=0; i<n; i++)
(Note that I changed the code above to fix this error).
However ultimately, that entire loop to figure out the largest can be accomplished with a single line of code using the std::max_element function:
#include <algorithm>
//...
int largest = *std::max_element(p, p + n);
and if using std::vector:
#include <algorithm>
//...
int largest = *std::max_element(p.begin(), p.begin() + n);
I've commented on suggested changes in this slightly modified version:
#include <iostream>
int main()
{
unsigned n; // don't allow a negative amount of numbers
if(std::cin >> n) { // check that "cin >> n" succeeds
int* p=new int[n]; // allocate an array of n ints instead of one int with value n
for(int i=0; i < n; ++i) { // corrected bounds [0,n)
if(not (std::cin >> p[i])) return 1; // check that "cin >> ..." succeeds
}
int largest = p[0];
for(int i=1; i < n; ++i) { // corrected bounds again, [1,n)
if(largest < p[i])
largest = p[i];
}
delete[] p; // free the memory when done
std::cout << largest << '\n';
}
}
Note that using *(p + i) does the same as using p[i]. The latter is often preferred.
This would work if all cin >> ... works, but shows some of the hazards when using raw pointers. If extracting the n ints failes, the program will return 1 and leak the memory allocated with new int[n].
A rewrite using a smart pointer (std::unique_ptr<int[]>) that automatically deallocates the memory when it goes out of scope:
#include <iostream>
#include <memory> // std::unique_ptr
int main()
{
unsigned n;
if(std::cin >> n) {
std::unique_ptr<int[]> p(new int[n]);
for(int i=0; i < n; ++i) { // corrected bounds [0,n)
if(not (std::cin >> p[i])) return 1; // will not leak "p"
}
int largest = p[0];
for(int i=1; i < n; ++i) {
if(largest < p[i])
largest = p[i];
}
std::cout << largest << '\n';
} // p is automatically delete[]ed here
}
However, it's often convenient to store an array and its size together and to do this, you could use a std::vector<int> instead. It comes with a lot of convenient member functions, like, size() - and also begin() and end() which lets you use it in range-based for loops.
#include <iostream>
#include <vector> // std::vector
int main()
{
unsigned n;
if(std::cin >> n) {
std::vector<int> p(n); // a vector of n ints
// a range-based for loop, "elem" becomes a refrence to each element in "p":
for(int& elem : p) {
if(not (std::cin >> elem)) return 1;
}
int largest = p[0];
for(int i = 1; i < p.size(); ++i) { // using the size() member function
if(largest < p[i])
largest = p[i];
}
std::cout << largest << '\n';
}
}
That said, you don't need to store any number in an array to figure out what the largest number is. Instead, just compare the input with the currently largest number.
#include <iostream>
#include <limits> // std::numeric_limits
int main()
{
unsigned n;
if(std::cin >> n) {
// initialize with the smallest possible int:
int largest = std::numeric_limits<int>::min();
while(n--) {
int tmp;
if(not (std::cin >> tmp)) return 1;
if(largest < tmp)
largest = tmp;
}
std::cout << largest << '\n';
}
}
i need to initialize my code during runtime the program is searching for how many times is the number in multiplication table
#include <iostream>
using namespace std;
int main()
{
int x = 0, n = 1 , count=0 ;
cin >> n>>x;
int arr[n][n];
for (int i = 0; i <n-1 ; i++) {
for (int j = 0; j <n-1 ; j++) {
cin >> arr[i][j];
if(arr[i][j]==x)count++;
}
}
cout<<count;
}
because i am getting error
did in i need in my c++ code to use vectors or learn STL?
The answer depends on your objective.
If you want to accomplish a programming task at hand in the most expedient manner, use std::vector.
If you want to learn how to manage allocation and dealloction of dynamic memory, learn about new and delete and use them instead of int arr[n][n];
I think by multiplication table you mean to say matrix.
For this particular problem you don't need even the matrix. You can just do by using a temporary variable. Something like this:
#include <iostream>
int main() {
int n, x, count = 0, tmep;
std::cin >> n >> x;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
std::cin >> temp;
if (temp == x) ++count;
}
std::cout << count;
}
You aren't getting proper answer probably because you are not reading the complete matrix. Your loops run from i = 0 to i < n - 1 (same for j). You need to either change < to <= or n - 1 to n.
If you need to re-use the inputted matrix, then probably an approach like this will be good:
#include <iostream>
#include <vector>
int main() {
int n, x, count = 0;
std::cin >> n >> x;
std::vector<std::vector<int>> mat(n, std::vector<int>(n));
for (auto &row : mat)
for (auto &ele : row) {
std::cin >> ele;
if (ele == x) ++count;
}
std::cout << count;
}
In any case something like arr[n][n] is not recommended as variable-length arrays are not supported by the standard itself, although some compilers like g++ do so.
#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.
I was trying to solve this question
but codechef.com says the answer is wrong.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t, n, diff, mindiff;
cin >> t;
cin >> n;
int val[n];
while(t--)
{
mindiff = 1000000000;
for(int i = 0; i<n; i++)
{
cin >> val[i];
}
int a = 0;
for(a = 0; a<n ; a++)
{
for(int b=a+1; b<n ; b++)
{
diff = abs(val[a] - val[b]);
if(diff <= mindiff)
{
mindiff = diff;
}
}
}
cout << mindiff << endl;
}
return 0;
}
The results are as expected (for at least the tests I did) buts the website says its wrong.
There are a few things in your code that you should change:
Use std::vector<int> and not variable-length arrays (VLA's):
Reasons:
Variable length arrays are not standard C++. A std::vector is standard C++.
Variable length arrays may exhaust stack memory if the number of entries is large. A std::vector gets its memory from the heap, not the stack.
Variable length arrays suffer from the same problem as regular arrays -- going beyond the bounds of the array leads to undefined
behavior. A std::array has an at() function that can check boundary access when desired.
Use the maximum int to get the maximum integer value.
Instead of
mindif = 1000000000;
it should be:
#include <climits>
//...
int mindiff = std::numeric_limits<int>::max();
As to the solution you chose, the comments in the main section about the nested loop should be addressed.
Instead of a nested for loop, you should sort the data first. Thus finding the minimum value between two values is much easier and with less time complexity.
The program can look something like this (using the data provided at the link):
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
int main()
{
int n = 5;
std::vector<int> val = {4, 9, 1, 32, 13};
int mindiff = std::numeric_limits<int>::max();
std::sort(val.begin(), val.end());
for(int a = 0; a < n-1 ; a++)
mindiff = std::min(val[a+1] - val[a], mindiff);
std::cout << mindiff;
}
Output:
3
To do this you can use a simple for():
// you already have an array called "arr" which contains some numbers.
int biggestNumber = 0;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] > biggestNumber) {
biggestNumber = arr[i];
}
}
arr.size will get the array's length so that you can check every value from the position 0 to the last one which is arr.size() - 1 (because arrays are 0 based in c++).
Hope this helps.