Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

my program is showing some error and is not executing

0 votes
asked Jan 25, 2022 by siddhi uniyal (120 points)
#include<stdio.h>

int main()

{

int n,a[n],i;

printf("enter value of n \n");

scanf("%d",&n);

printf("enter array elements \n");

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

{

scanf("%d",&a[i]);

}

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

{   if (a[i]%2==0){

printf("even elements are %d \n",a[i]);

}

else

printf("odd elements are %d \n",a[i]);

return 0;

}

}

1 Answer

+2 votes
answered Feb 22, 2022 by Peter Minarik (86,180 points)
edited Feb 25, 2022 by Peter Minarik

The problem is that you initialize your array (a[])  to have the size of n before you'd assign any size to the variable n. If you do not assign any value to a variable, it will hold some random value (a.k.a. memory garbage). This is why your code does not work.

To make it work, declare your array after the user has provided the desired size for it.

Your code correctly:

#include <stdio.h>

int main()
{
    int n;
    printf("enter value of n \n");
    scanf("%d",&n);
    printf("enter array elements \n");
    
    int a[n]; // Declare your array when the value of n is known.
    
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }

    for (int i = 0; i < n; i++)
    {
        if (a[i] % 2 == 0)
        {
            printf("even elements are %d \n", a[i]);
        }
        else
        {
            printf("odd elements are %d \n", a[i]);
        }
    }
    
    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...