C Exercises: Compute the sum of consecutive odd numbers from a given pair of integers
C Basic Declarations and Expressions: Exercise-34 with Solution
Write a C program to compute the sum of consecutive odd numbers from a given pair of integers.
Sample Solution:
C Code:
#include <stdio.h>
int main() {
int x, y, i, total = 0; // Declare variables for user input and calculations
printf("\nInput a pair of numbers (for example 10,2):");
printf("\nInput first number of the pair: ");
scanf("%d", &x); // Read the first number
printf("\nInput second number of the pair: ");
scanf("%d", &y); // Read the second number
if (x < y) {
return 0; // If x is less than y, exit the program
}
printf("\nList of odd numbers: ");
for (i = y; i <= x; i++) {
if ((i % 2) != 0) {
printf("%d\n", i); // Print odd numbers within the range
total += i; // Add odd numbers to the total
}
}
printf("Sum=%d\n", total); // Print the total sum
return 0;
}
Sample Output:
Input a pair of numbers (for example 10,2): Input first number of the pair: 10 Input second number of the pair: 2 List of odd numbers: 3 5 7 9 Sum=24
Flowchart:
C programming Code Editor:
Previous: Write a C program that accepts some integers from the user and find the highest value and the input position.
Next: Write a C program to check if two numbers in a pair is in ascending order or descending order.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/basic-declarations-and-expressions/c-programming-basic-exercises-34.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics