Write a program to calculate and print the sum of odd numbers and the sum of even number for first 'n' natural number
Answers
Answer:
I hope u asked for c++ program if not mention the language
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i, num; //declare variables i, num
int oddSum=0,evenSum=0;
//declare and initialize variables oddSum,evenSum
cout<<"Enter the value of num \n";
cin>>num;
for(i=1; i<=num; i++){// for loop use to iterate 1 to num
if(i%2==0) //Check even number for sum
evenSum=evenSum+i;
else
oddSum=oddSum+i;
}
cout<<"Sum of all odd numbers are:"<< oddSum;
cout<<"\nSum of all even numbers are:"<<evenSum;
getch();
return 0;
}
Explanation:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,s=0,m=0;
cout<<"Enter a number:";
cin>>n;
for(int i=1;i<=n;i++)
{
if(i%2= =0)
s=s+i;
else
m=m+i;
}
cout<<"Sum of even no."<<s<<endl;
cout<<"Sum of odd no."<<m;
getch();
}