Home > Mobile >  How to Get the Sum of Elements in Array without including Elements less than 80
How to Get the Sum of Elements in Array without including Elements less than 80

Time:11-23

I am working with this code that computes the sum of array when I got an idea how to exclude the elements of array that are below 80.

the statement ( if (a[x] < 80) ) is not working

Below is the code

#include<stdio.h>
#include<conio.h>
#define p printf

main()
{
clrscr();
int a[10], x, sum=0;
p("\nEnter 10 numbers greater than 80: ");
for(x=0; x<10; x  )
    scanf("%d", &a[x]);

for(x=0; x<10; x  )
    sum=sum a[x];
    p("The sum is %d", sum);
getch();
return 0;
}

CodePudding user response:

You currently have, as pseudocode,

for(each element in the array)
    add it into 'sum'

What you want is

for(each element in the array)
    if(it's greater than 80)
        add it into 'sum'

So now you just need the right C syntax to do this. There's a wrong way and a right way to go about it.

Wrong way: type in random guesses, perhaps informed by your knowledge of some programming language other than C, hoping for something that will work.

Right way: read the first one or two chapters of your introductory C textbook or tutorial carefully. All the information you'll need is, I guarantee it, in there. It will take you a few hours to read, but that'll be much, much less time (and frustration!) than you'll spend trying to learn C by trial and error. C is not a language to learn by trial and error!

CodePudding user response:

you should change your code into this:

for(x=0; x<10; x  ){
    if( a[x] > 80){
        sum=sum a[x];
    }
}
printf("The sum is %d", sum);
  • Related