C++ code don't have errors but not giving output [closed]

Solution 1:

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.