0

WAP to sort an array in ascending order. Issue: After Sorting the array getting the garbage value in the compiler. Also when done without a function compiler return nothing

#include<stdio.h>   
//Global Decleration   
int i, j, size;   
//Function for bubble sort   
int bubblesort(int arr[size]){  
    int temp;  
    printf("The numbers arranged in ascending order are given below: \n");  
    for(i=0;i<size-1;i++){  
        for(j=0;j<size-1-i;j++){  
            if(arr[j]>arr[j+1]){  
                temp=arr[j];  
                arr[j]=arr[j+1];  
                arr[j+1]=temp;  
            }  
        }  
    }  
    for(j=0;j<size;j++)  
        printf("%d\n",arr[j]);  
}   
int main(){   
    int size, arr[size];    
    printf("Enter the number of elements of the array: \n");   
    scanf("%d", &size);    
    printf("Enter the numbers: \n");    
    for(i=0;i<size;i++){   
        scanf("%d", &arr[i]);    
    }   
    bubblesort(arr[size]);     
}
RAHUL
  • 11
  • 1
    `size` is uninitialized. Turn on compiler warnings. The things you seem to think are the compiler are actually your compiled program being executed. The things you _should_ be seeing are the compiler screaming at you about uninitialized values because you've enabled all warnings. – paddy Mar 28 '22 at 12:18
  • 1
    Aside: this global use of variables is one of the least justifiable you could find! Anyway the `size` in `main` is *shadowing* the global `size`. – Weather Vane Mar 28 '22 at 12:18
  • 1
    `bubblesort(arr[size]);` accessing out of bounds data. Turn on compiler warnings. – जलजनक Mar 28 '22 at 12:19
  • Note that the global variable `size` is unrelated to the local variable `size` defined in `main()`. The global variable is zero. The design of the interface to `bubblesort()` is broken — you need an interface more like `void bubblesort(size_t size, int arr[size])`, passing the array size explicitly. There's no value to return, so using `void` is appropriate. You should separate the printing from the `bubblesort()` function, too. – Jonathan Leffler Mar 28 '22 at 12:20
  • 2
    Another minor: try to keep *form* and *function* separate. The sorting function should really be silent - the reporting should be done by the caller. – Weather Vane Mar 28 '22 at 12:21
  • Worth understanding [runtime vs. compile time](https://www.baeldung.com/cs/runtime-vs-compile-time) and [here](https://stackoverflow.com/questions/846103/runtime-vs-compile-time). – jarmod Mar 28 '22 at 18:59

0 Answers0