- 2071 Chaitra · 4 marks
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)
Related questions
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Function definition; sum of two numbers · Computer Programming, chapter 6
- GOTO types; sum of series program · Computer Programming, chapter 11
- Correct program: case array and average · Computer Programming, chapter 3
- Algorithm for numbers divisible by 9 not 6 · Computer Programming, chapter 2
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- 8086 ALP: sum of 100 even numbers · Microprocessor, chapter 3
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3