+ 4

Can anyone find out why this code outputting a garbage value instead of sum of even numbers in the list?

#include <stdio.h> int main() { int sum=0,N,a[20]; printf ("enter the no.of elements"); scanf("%d",&N); for(int k=0;k<N;k++){ scanf("%d",&a);} for(int i=1;i<N;i++) { if(a[i]%2==0) sum=sum+a[i]; } printf("sum of even numbers =%d",sum); return 0; }

28th Apr 2021, 11:25 AM
Hemasri Kottapalli
Hemasri Kottapalli - avatar
8 Respostas
0
Yeah I find it in second loop you run from 1 it should be from 0
28th Apr 2021, 12:47 PM
YUGRAJ
+ 2
Thx for your response however i don't think so! Cuz in scanf I had to mention array variable NAME where I wanna store my elements and here below a[i] I indicates index of array elements everytime the for loop iterates!
28th Apr 2021, 11:48 AM
Hemasri Kottapalli
Hemasri Kottapalli - avatar
28th Apr 2021, 11:48 AM
Hemasri Kottapalli
Hemasri Kottapalli - avatar
+ 2
I did but it's not giving right answer! May be another bug is there?YUGRAJ
28th Apr 2021, 12:24 PM
Hemasri Kottapalli
Hemasri Kottapalli - avatar
+ 1
I think you forget a[i] in scanf
28th Apr 2021, 11:43 AM
YUGRAJ
+ 1
Ya thank you so much for your help😊YUGRAJ
28th Apr 2021, 1:22 PM
Hemasri Kottapalli
Hemasri Kottapalli - avatar
0
Sorry you have to write there scanf("%d", &a[k]) ; Try this
28th Apr 2021, 12:04 PM
YUGRAJ
0
#include <stdio.h> int main() { int sum=0,N,a[20],k,i; printf ("enter the no.of elements"); scanf("%d",&N); for(k=0;k<N;k++){ printf("le %d number is",k+1); scanf("%d",&a[k]); } for(i=0;i<N;i++) { if(a[i]%2==0) sum=sum+a[i]; } printf("sum of even numbers =%d",sum); return 0; }
30th Apr 2021, 7:04 AM
Malek
Malek  - avatar