Write a program that takes 10 integers and outputs the sum of the odd-numbered integers and the even-numbered integer.
The sentence above is the problem and I made the code.
#include <stdio.h>
int main() {
int arr[10];
int i;
int odd,even=0;
for(i=0;i<10;i++){
scanf(" %d",&arr[i]);
}
for(i=1;i<=10;i++){
if(i%2!=0) odd+=arr[i-1];
else even+=arr[i-1];
}
printf("odd : %d\n",odd);
printf("even : %d\n",even);
return 0;
}
The second for statement is that if the value of i is odd, then the value of i-1 is stored in the index is stored in the OD value, and if it is even, the code is created
The even variable part is output correctly, but the od part is not output correctly(Crying)
(For example, if you enter 1020256683722901100, the odd part of the od is output)
It's my first time coding, so I don't know where the error occurred Please!
array
intodd,even=0;
is invalid. The odd must also be initialized to zero. Modify to intodd=0, even=0;
and try running it.
Please refer to the code below.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int arr[10];
int i;
int odd = 0, even = 0;
for (i = 0; i < 10; i++) {
scanf(" %d", &arr[i]);
}
for (i = 1; i <= 10; i++) {
if (i % 2 != 0) odd += arr[i - 1];
else even += arr[i - 1];
}
printf("odd : %d\n", odd);
printf("even : %d\n", even);
return 0;
}
© 2024 OneMinuteCode. All rights reserved.