Write a C++ program to find the sum of even and odd n natural numbers
Question
Write a C++ program to find the sum of even and odd n natural numbers
Solution
Sure, here is a simple C++ program that calculates the sum of even and odd numbers up to a given number 'n'.
#include<iostream>
using namespace std;
int main() {
int n, sumEven = 0, sumOdd = 0;
cout << "Enter a number: ";
cin >> n;
for(int i = 1; i <= n; i++) {
if(i % 2 == 0)
sumEven += i;
else
sumOdd += i;
}
cout << "Sum of even numbers: " << sumEven << endl;
cout << "Sum of odd numbers: " << sumOdd << endl;
return 0;
}
This program works as follows:
- It first asks the user to enter a number 'n'.
- It then initializes two variables,
sumEvenandsumOdd, to 0. These variables will hold the sum of the even and odd numbers, respectively. - It then enters a loop that runs from 1 to 'n'. For each number 'i' in this range, it checks if 'i' is even or odd by using the modulus operator (
i % 2). - If 'i' is even (i.e.,
i % 2 == 0), it adds 'i' tosumEven. Otherwise, it adds 'i' tosumOdd. - After the loop finishes, it prints the sum of the even and odd numbers.
Similar Questions
Write a C++ program to find the sum of even and odd n natural numbers
Write a program to accept an integer N and print the sum of first N odd numbersInput Format:An integer range is given inputOutput Format:Print only calculated sum.Constraints:1 <= N <= 10^16 Sample Input 1:2Sample Output 1:4Sample Input 2:10Sample Output 2:100
Write down the C code for the following questions.a) Write a program in C to check if a given number is even or odd using the function.b) Write a program in C to swap two numbers using a function.c) Write a program in C to find the square of a number using the function.d) Write a program in C to find the factorial of a number using the function.e) Write a program in C to calculate the area of circle using the function.f) Write a C program to compute the sum of the first “N” natural numbers using thefunction.g) Write a program in C to print the Fibonacci series using the function.
Program to ask a user for supplying n different integers and countthe total number of even and odd values among them
Sum of EvenSend FeedbackProblem Statement:Write a program that takes a tuple as input and prints the sum of all the even numbers in the tuple.Input:A tuple containing integer elements.Output:The sum of all the even numbers in the tuple.Sample Input:(2, 3, 4, 6, 7)Sample Output:12
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.