Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading