Home > Software engineering >  How do I find the arithmetic middle of these numbers in C?
How do I find the arithmetic middle of these numbers in C?

Time:11-08

So I'm trying to write a program that prints out all three-digit numbers which have their last digit divisible by 3.

And then prints out the arithmetic middle of all those numbers, so sum of all those numbers divided by the number of them.

I tried doing it like this, but it's not correct and I'm stuck.

#include <stdio.h>

int main(void)
{

    int i, a, sum, middle;

    for (i = 100; i < 1000; i  ){
        a = i;
        if (a == 3 || a == 6 || a == 9)
        printf ("%d\n", i);
         sum = i;
    }
    printf("\n%d", sum);
    middle= sum/ i;
    printf("\n%d", middle);
    return 0;
}

CodePudding user response:

I think you are missing { } around your if statement nested in the for loop. If you want more than one line to be executed if an 'if' evaluates to true, you need to wrap those lines in curly brackets { } just like you wrapped the for loop. so you can try:

#include <stdio.h>

int main(void)
{

    int i, a, sum = 0, middle;

    for (i = 100; i < 1000; i  ){
        a = i;
        if (a == 3 || a == 6 || a == 9){
           printf ("%d\n", I);
           sum = i;
        } 
    }
    printf("\n%d", sum);
    middle= sum/ i;
    printf("\n%d", middle);
    return 0;
}

all you also need to initialize sum to 0 because you are using = in the for loop to assign to sum. otherwise i will be added to a garbage value

CodePudding user response:

This is the solution:

#include <stdio.h>

int main(void)
{

    int i, a, sum = 0, middle, numCount = 0;

    for (i = 100; i < 1000; i  ){
        a = i;
        if (a == 3 || a == 6 || a == 9){
        printf ("%d\n", i);
        sum  = i;
        numCount  = 1;
    }
}

    printf("\n%d", sum);

    middle  = sum / numCount;
    printf("\n%d", middle);

    return 0;
}

  • Related