Skip to main content

Sum and average between M and N using pointer

Short answer

Read M and N through pointers, loop from *pm to *pn summing values and counting them. If count>0, print sum and average (sum/count as float), else print error. Example: for M=3, N=9, sum=42, average=6.00.

Write program to calculate sum and average of integer numbers between M and N (where value of M and N are read from keyboard) using pointer.

Logic. M and N are read through pointers (pm = &m, pn = &n). A loop runs from *pm to *pn, adding each number and counting how many there are. Average = sum / count, calculated in float. If M is greater than N, the range is empty and a message is shown. M and N are included in the sum.

#include <stdio.h>

int main(void)
{
    int m, n, sum = 0, count = 0;
    int *pm = &m, *pn = &n;               /* pointers to M and N */

    printf("Enter M and N: ");
    scanf("%d %d", pm, pn);

    for (int i = *pm; i <= *pn; i++) {
        sum += i;
        count++;
    }
    if (count > 0)
        printf("Sum = %d, Average = %.2f\n", sum, (float)sum / count);
    else
        printf("M should not be greater than N\n");
    return 0;
}

Sample run (3 to 9: 3 + 4 + … + 9 = 42 over 7 numbers)

Input: 3 9

Enter M and N: Sum = 42, Average = 6.00

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →