C Exercises: Sequence from the lowest to highest number and average value of the sequence
Print sequence between two numbers and calculate its average
Write a C program that accepts a pair of numbers from the user and prints the sequence from the lowest to the highest number. Also, print the average value of the sequence.
Sample Solution:
C Code:
#include <stdio.h>
int main () {
int p, x = 1, y = 1, i = 0, temp = 0;
float sum_val = 0;
// Prompt user for input
printf("Input two pairs values (integer values):\n");
// Read two integer values from user and store them in 'x' and 'y'
scanf("%d %d", &x, &y);
// Check if both 'x' and 'y' are positive
if (x > 0 && y > 0) {
// Swap 'x' and 'y' if 'y' is smaller than 'x'
if (y < x) {
temp = x;
x = y;
y = temp;
}
printf("\nSequence from the lowest to highest number:\n");
// Loop to print and accumulate values from 'x' to 'y'
for (p= 0, i = x; i <= y; i++) {
sum_val += i; // Accumulate the values for average calculation
printf("%d ", i);
p++;
}
// Print the average value of the sequence
printf("\nAverage value of the said sequence\n%9.2f", sum_val / p);
}
return 0; // End of program
}
Sample Output:
Input two pairs values (integer values): 14 25 Sequence from the lowest to highest number: 14 15 16 17 18 19 20 21 22 23 24 25 Average value of the said sequence 19.50
Sample Output:
Input two pairs values (integer values): 35 13 Sequence from the lowest to highest number: 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Average value of the said sequence 24.00
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to generate a sequential series between two integers and compute the arithmetic mean of the sequence.
- Write a C program to print all numbers between two limits and calculate their average using an iterative approach.
- Write a C program to store the sequence in an array, then compute and print the average using pointer arithmetic.
- Write a C program to use a function that both prints the sequence from min to max and returns the calculated average.
Go to:
PREV : Sum of even numbers between two integers.
NEXT : Check if two integers are in ascending or descending order.
C programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.