Default element value is used instead of user defined in C?

76 views Asked by At

I am beginner in C. I have been writing a program code to find largest element in Array. Passed Value is not able to store in array of type: float. Instead default Value:0 is being stored. What to do?

#include <stdio.h>

// Largest Element

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

    printf("Enter Element Count in range(1,100):-");
    scanf("%d",&n);

    while(n>100 || n<1){
        printf("Enter Element Count in range(1,100) again:-");
        scanf("%d",&n);
    }

    for(i=0; i<n;i++){
        printf("Enter Element:-");
        scanf("%f",&arr[i]);
    }

    for(int k=0;k<n;k++){
        printf("Element-%d:-%d\n",k+1,arr[k]);
    }

    for(int j=0;j<n;j++){
        
        for(int k=j+1;k<n;k++){
            
            if (arr[j] < arr[k]){
                break;
            }
            else{
                printf("Largest Element:-%d\n",arr[j]);
                break;
            }
        }
        continue;   
    }

    return 0;
}

OUTPUT SCREEN

2

There are 2 answers

1
Vlad from Moscow On BEST ANSWER

To output values of the type float you have to use the conversion specifier f. The conversion specifier d is designed to output integer values.

So these calls of printf

printf("Element-%d:-%d\n",k+1,arr[k]);

and

printf("Largest Element:-%d\n",arr[j]);

are incorrect. You have to write

printf("Element-%d:-%f\n",k+1,arr[k]);

and

printf("Largest Element:-%f\n",arr[j]);

Also if you are going to find the largest element in the array then these for loops do not make a sense.

for(int j=0;j<n;j++){
    
    for(int k=j+1;k<n;k++){
        
        if (arr[j] < arr[k]){
            break;
        }
        else{
            printf("Largest Element:-%d\n",arr[j]);
            break;
        }
    }
    continue;   
}

At least for example the continue statement is redundant. And the inner for loop is also redundant because it is interrupted at once due to break statements in the if-else statement.

The largest element is searched the following way using only one for loop.

int largest = 0;

for ( int i = 1; i < n; i++ )
{
    if ( arr[largest] < arr[i] ) largest = i;
}

printf( "Largest Element:-%f at position %d\n",arr[largest], largest );
1
ioannis-kokkalis On

Explanation In the two cases below you are using %d to print a float number. That's why you are getting 0 printed and not the actual number.

Use %f like you did for reading the value on scanf earlier instead of %d for the float values.

printf("Element-%d:-%d\n",k+1,arr[k]);
printf("Largest Element:-%d\n",arr[j]);