sumitpal0593
sumitpal0593

Reputation: 334

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:

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

int checkInversions(int arr[], int n) {
    int i, j, inverse_count = 0;

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

int main() {
    int arr[10], i, n;

    printf("Enter the elements of the array: %d");

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

    n = sizeof(arr) / sizeof(arr[0]);   

    printf("\n The inverse is: %d", checkInversions(arr, n));

    return 0;
}

Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.

Upvotes: 1

Views: 1260

Answers (3)

Zee
Zee

Reputation: 21

Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

Upvotes: 1

Federico Montoli
Federico Montoli

Reputation: 11

I think you are missing the variable that should populate the %d on the printf. Try taking out the %d on the printf call so it ends up like:

printf("Enter the elements of the array: ");

Or assign the corresponding variable to display with that "%d", like this:

printf("Enter the elements of the array: %d", variable);

Check if that helps!

Upvotes: 1

Govind Parmar
Govind Parmar

Reputation: 21532

You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.

What you meant to do was merely:

printf("Enter the elements of the array: ");

Also, since arr has 10 elements, you iterate through it as such:

for(i = 0; i < 10; i++)

You don't need to use sizeof to determine the size of the array since you already know it; it's 10.

Upvotes: 2

Related Questions