i wanted to this time, using the same x[] array to write a f or loop that sums the even-numbered elements(elements 0, 2, and 4) from the list. eg sum would be 126
(30 + 51 + 45.)
Here are my codes for each part but i dont know why it's not giving me the desired values. please help!!
part a
#include<stdio.h>
#include<conio.h>
#define N 6
int main()
{
int x[] = {30, 12, 51, 17, 45, 62,};
int i ;
int sum = 0;
i wrote the code as a solution to the part b but it didn't print anything. could you tell me why? Also, explain the algorithm of my code for me to better understand arrays. i mean start with the for loop and the loop content.
#include<stdio.h>
#include<conio.h>
#define N 6
int main()
{
int x[] = {30, 12, 51, 17, 45, 62,};
int i ;
int sum=0;
for(i=0; i<N;i+2)
{
sum+= x[i];
}
printf("%2d", sum);
getche();
}
ANSWER: Hi,
#include<stdio.h>
#include<conio.h>
#define N 6
int main()
{
int x[] = {30, 12, 51, 17, 45, 62,};
int i ;
int sum=0;
//When you do a i+2 here, the counter increases by 2 every time. So, it should sum up x[0] + x[2] + x[4] + x[6] + x[8] + x[10].
for(i=0; i<N;i+2)
{
sum+= x[i];
}
printf("%2d", sum);
getche();
}
HTH.
---------- FOLLOW-UP ----------
QUESTION: Hello Kaustav,
Exactly what i was expecting but i think it will only sum up x[0] + x[2] + x[4]but i think it will keep incrementing up to x[10] from what i just inferred from your explanation. therefore, how would i have done it?
Answer Like this -
#include<stdio.h>
#include<conio.h>
#define N 6
int main()
{
int x[] = {30, 12, 51, 17, 45, 62,};
int i ;
int sum = 0;