-2

I am new to C programming, This is my simple c program. It compiled successfully, but it is not executing, I don't know where is the problem. Please help me out.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void bub_sort();
int arr[50], n;

void main()
{
    int i, j;

    system("cls");

    printf("Enter the numbers count: ");
    scanf("%d", &n);

    printf("Enter the %d integers: \n", n);

    for(i=0; i<n; i++)
    {
        scanf("%d", &arr[i]);
    }

    bub_sort();

    printf("\nIntegers in ascending order: \n");

    for(j=0; j<n; j++)
    {
        printf("%d\t", arr[i]);
    }

    getch();
}

void bub_sort()
{
    int i, j;

    for(i=0; i<n; i++)
    {
        for(j=0; i<n-1; j++)
        {
            if(arr[i] > arr[i+1])
            {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
    }
}

This program is getting input successfully but after that, it freezes up.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 3
    Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you probably want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Andreas Wenzel Dec 18 '20 at 02:40
  • 3
    Just as a side note: It is unsafe to use `scanf` without checking the return value. See this page for further information: [A beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) – Andreas Wenzel Dec 18 '20 at 02:41
  • 2
    Tip: Don't use global variables without a compelling reason.This code would be way easier to follow if those weren't global. Do try and declare your variables in the context in which they're used, like `for (int i = 0; ...)` is way better than `for (i = 0;` and then we have to go looking for a defintion of `i` somewhere. – tadman Dec 18 '20 at 02:41
  • What is the input you're using? – Daniel Walker Dec 18 '20 at 02:43
  • 1
    Use a debugger. There are many free ones. This question is the very essence of "no research effort." – TomServo Dec 18 '20 at 02:46

1 Answers1

4

It seems that the second for falls into an infinite loop in the bub_sort function

for(j=0; i<n-1; j++)

because you are using i instead of j in your condition.

zavg
  • 10,351
  • 4
  • 44
  • 67